Recommend Using ThreadLocal to pass context information around in web applications (Email)

This action will generate an email recommending this article to the recipient of your choice. Note that your email address and your recipient's email address are not logged by this system.

EmailEmail Article Link

The email sent will contain a link to this article, the article title, and an article excerpt (if available). For security reasons, your IP address will also be included in the sent email.

Article Excerpt:
Hi, In java web servers, each http request is handled by a thread in thread pool. So for a Servlet handling the request, a thread is assigned. It is tempting (and very convinient) to keep context information in the threadlocal variable. I recently had a requirement where we need to assign logged in user id and timestamp to request sent to web services. Because we already had the code in place, it was extremely difficult to change the method signatures to pass user id everywhere. The solution I thought is class ReferenceIdGenerator { public static setReferenceId(String login) { threadLocal.set(login + System.currentMillis()); } public static String getReferenceId() { return threadLocal.get(); } private static ThreadLocal threadLocal = new ThreadLocal(); } class MySevlet { void service(.....) { HttpSession session = request.getSession(false); String userId = session.get("userId"); ReferenceIdGenerator.setRefernceId(userId); try { doSomething(); } finally { ReferenceIdGenerator.remove(); } } This method is also discussed at http://crazybob.org/2006/07/hard-core-java-threadlocal.html Is this a reasonable approach to pass context information in web application? Can this ever happen that while a http request is being processed in the thread, a thread is suddenly assigned to some other tasks? I hope this can never happen, because app servers themselves rely heavily on threadlocals to keep transaction related information around. What do you think? Thanks, Unmesh


Article Link:
Your Name:
Your Email:
Recipient Email:
Message: