aspose file tools*
The moose likes Threads and Synchronization and the fly likes is ThreadLocal devil in clustering environment? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Java » Threads and Synchronization
Bookmark "is ThreadLocal devil in clustering environment?" Watch "is ThreadLocal devil in clustering environment?" New topic
Author

is ThreadLocal devil in clustering environment?

Will Lee
Ranch Hand

Joined: Mar 16, 2005
Posts: 58
I'm not quite familiar with ThreadLocal class. What I need to do is pass a parameter to all methods in all service classes. So it become good candidate to use ThreadLocal to save this context info. However it is suggested in the office that ThreadLocal should be absolutely forbid in clustering j2EE application server environment due to the "clustering". Anyone have argument to support or against this statement?


SCJP 1.4, SCWCD, SCDJWS
Ernest Friedman-Hill
author and iconoclast
Marshal

Joined: Jul 08, 2003
Posts: 24187
    
  34

"Clustering" refers to running an application on multiple machines for capacity purposes. J2EE has some elaborate mechanisms built in that allow objects to be transparently migrated from one machine to another in a cluster. Any dependence on the specific JVM in which an object lives -- such as using static variables, or ThreadLocals (which are effectively another kind of global variable) -- breaks these mechanisms. Don't do it.


[Jess in Action][AskingGoodQuestions]
Will Lee
Ranch Hand

Joined: Mar 16, 2005
Posts: 58
Thank you Ernest very much for the reply. It's very helpful for my design.
Will Lee
Ranch Hand

Joined: Mar 16, 2005
Posts: 58
I've been given a thought over weekend. And I'm still a bit confused. Since all the methods call in my application is invoked by one request from browser, therefore these methods invocation should live and die w/ the thread w/in the single JVM. This thread for servlet request will never propagate across the cluster. Why can't use threadLocal?

I'm not use ThreadLocal to save class level object, I just want it to keep the method context (not session context or anything else) so that my next method w/in same thread will get it. Therefore I don't have to pass this context to all my methods. Is is feasible?
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: is ThreadLocal devil in clustering environment?