What is the typical use of ThreadLocal in java. When does on开发者_StackOverflowe use it? I couldn't application details from this java docs article.
I'd say that the most typical ThreadLocal usage is when you have some object that has to be accessible everywhere during one flow and you do not want to pass reference to this object over all layers. Something like singleton pattern but per thread.
The examples are DB connection, hibernate session etc. You open them somewhere in the beginning of your flow, commit/close in the end of the flow and use everywhere during the flow.
Is for when you want to use objects that are not thread safe, but don't want to synchronize access to them (for performance reasons). More or less, you create an accessor for the object you need to use multiple times, so that you ensure that every thread that might call that accessor gets a different, unused one. A very typical use is for using SimpleDateFormat, which is a class that if it were thread safe, your instance would be declared as static, in order to reuse the same instance.
Here's a good article describing it: Dr. Dobbs: Using Thread-Local Variables In Java
Maybe more illustrative example can be good for you:
method1(): ... method2(somedata) ...
method2(somedata): ... method3(somedata) ...
method3(somedata): ... method4(somedata) ...
method4(somedata): ... do something with somedata ...
Such situations occur for example in multi-layered architectures (UI calls remote facade, remote facade calls application layer, application layer calls domain layer, domain layer calls persistence layer, ...) If those methods () belong to different classes there's no good way to pass such data except adding extra parameter 'somedata' for most methods in our code, this breaks eg open-closed principle. The solution to this problem is ThreadLocal:
method1(): ... threadLocal.set(somedata); method2(); threadLocal.set(null); ...
method2(): ... method3() ...
method3(): ... method4() ...
method4(): ... do something with threadLocal.get() ...
If your flow is tied to a thread, like AlexR mentioned, you can create a public final class C
with a private static final ThreadLocal<T> p
property, add accessor methods. Then you can use p.set(), p.remove(), and p.get() respectively along your flow.
public final class C {
private static final ThreadLocal<String> p = new ThreadLocal<String>();
// initialize property at the begining of your thread (flow)
public static void set(final String s){
p.set(s);
}
// use property during the thread's lifecycle
// for instance: C.get().equals(myString)
public static String get(){
return p.get();
}
// remember to remove property from the thread when you're done, specially if it came from a thread pool
public static void remove(){
p.remove();
}
}
精彩评论