Advantage of Threadlocal over session object in web application. I can save all data related to particular user in Session object or Threadlocal ?. [ October 15, 2008: Message edited by: jacob deiter ]
They are not the same thing, since ThreadLocal is only valid for the duration of the request. You still need a session to maintain data between requests. The next request from the same user is unlikely to go to the same thread, so the ThreadLocal state will be either lost or invalid.
Originally posted by jacob deiter: Advantage of Threadlocal over session object in web application. I can save all data related to particular user in Session object or Threadlocal ?.
[ October 15, 2008: Message edited by: jacob deiter ]
Both could be used as data holders, but are drastically different coming to visibility/scope.
ThreadLocal is specific to a thread - meaning whatever info you put in here is not visible/accessible from other threads. On the other hand data kept in a Session is accessible to all threads part of that session.
If you need to manage some data, which you can not have as local variables then ThreadLocal is the way to go.
ThreadLocal is only valid for the duration of the request.
Since we're talking about servlets here, any ThreadLocal would likely be an instance (or static) variable of a servlet, since it doesn't really make sense to have a ThreadLocal as a local variable in a method. In that case it could potentially live for the lifetime of a servlet, not just for one request. That would depend on how the servlet container uses threads and thread pools, though.
Joined: Apr 02, 2008
Hi all thank for reply.I agree that threadlocal for a thread but I will make a threadlocal available for all threads from same user. My intention is as follow
1)when a new user come into the application ,I will create a threadlocal variable and place all service layer class into that
2) I should use session object to place all service object
"service object"? What are these? What is is you want to cache and why?
Another issue with using a ThreadLocal to store stuff in a servlet is how this would behave in a cluster. JEE containers are required to provide session replication between nodes, but no simmilar requirement exists for ThreadLocals.