在这里谈论 Java Servlet... 我正在创建自己的“每个请求上下文”,并且希望将“每个请求上下文”对象与 Thread.currentThread().getId() 值联系起来。
我计划在用户调用基于 Per Request 的函数并自动从该 threadId 的哈希表中获取 Context 对象时检查当前 threadid,而不是到处传递这个 context 对象。
我会使用这样的代码..
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
MyFramework.EnterContext();
try {
// do stuff here that leads to other classes on the same thread
// Access current context via static MyFramework.getCurrentContext()
}
finally { MyFramework.ExitContext(); }
}
但是,我想自动保护我的应用程序免受任何不调用 ExitContext() 的潜在用户的影响。在 C# 中有一个用于 onexit 的线程对象上的事件处理程序...(认为我错了)有没有办法在线程退出时检测或轮询?我目前只存储threadId(长)。
有任何想法吗?