How to determine the end of a thread through ThreadId?

Speaking Java servlets here ... I'm working on creating my own "Per Request Context", and I was looking to bind the "Request Context" object to the value of Thread.currentThread (). getId ().

Instead of going around this context object everywhere, I planned to check the current thread when the user calls a function based on the request and automatically gets the Context object from the hash table for this threadId.

I would use code like this.

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(); }
}

However, I would like to protect my application automatically from any potential user who does not call ExitContext (). In C # there is an event handler for the stream object for onexit ... (I think I'm wrong about this) is there a way to detect or poll when the stream exits? Currently I only save threadId (long).

Any ideas?

+3
source share
2 answers

unfortunatelly, there is no such function built-in for streams in Java. In addition, the thread identifier is only guaranteed to be unique at any given time, but can be reused in the end when the thread dies (from documents). however, the servlet structure you use can implement such a function (just speculation).

web.xml. , .

+1

A ThreadLocal, , . ThreadLocal . , , .

- :

private static final ThreadLocal<UserContext> userContext = new ThreadLocal<UserContext>();

public void doPost(HttpServletRequest request, HttpServletResponse response) 
              throws ServletException, IOException {
    MyFramework.EnterContext();
    try {
       UserContext context = userContext.get();
       //if you used the set method in this thread earlier
       //a thread local context would be returned using get
    }
    finally { MyFramework.ExitContext(); }
}

, , .

+1

All Articles