Using ThreadLocal to pass context information around in web applications


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");

   try {
   finally {

This method is also discussed at

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?