Can't we use local variables which are thread safe instead of ThreadLocal. and where ThreadLocal is being used. Pls quote some real application examples.
-
2Instead of us posting some random example, how about you posting your example?Rohit Jain– Rohit Jain2015-03-01 18:41:07 +00:00Commented Mar 1, 2015 at 18:41
-
Sometimes you probably can. They aren't the same thing though, so this depends on the behaviour you need in your specific case.Keppil– Keppil2015-03-01 18:42:49 +00:00Commented Mar 1, 2015 at 18:42
3 Answers
A typical example is SimpleDateFormat which is not thread safe. In a multi threaded context, two thread safe options are, among others:
private static ThreadLocal<SimpleDateFormat> fmtHolder = new ThreadLocal<SimpleDateFormat>() {
@Override protected SimpleDateFormat initialValue() {
return new SimpleDateFormat("dd/MM/yyyy");
}
};
private void method() {
SimpleDateFormat fmt = fmtHolder.get();
}
or using a local instance:
private void method() {
SimpleDateFormat fmt = new SimpleDateFormat("dd/MM/yyyy");
}
The former can be more efficient while the latter is easier to read and reason with.
Comments
A local variable can only be used in the function or block where it is declared, and it ceases to exist when the function returns or the block exits.
You use a ThreadLocal object, usually referenced from a static variable or from an instance variable of a singleton object, when you want static data, but you want each thread to have its own copy.
Comments
Thread local variable has different instances in different threads. This allows each thread to have it's own view of the variable that is independent of what other threads see. "Plain" local variable is a single instance and, when accessed in a thread-safe way, will have the same value in all threads.