Example & Tutorial understanding programming in easy ways.

What is ThreadLocal variable in Java?

ThreadLocal variables are special kind of variable available to Java programmer. Just
like instance variable is per instance, ThreadLocal variable is per thread.

It's a nice
way to achieve thread-safety of expensive-to-create objects, for example you can
make SimpleDateFormat thread-safe using ThreadLocal. Since that class is
expensive, its not good to use it in local scope, which requires separate instance on
each invocation. By providing each thread their own copy, you shoot two birds in one
arrow. First, you reduce number of instance of expensive object by reusing fixed
number of instances, and Second, you achieve thread-safety without paying cost of
synchronization or immutability. Another good example of thread local variable
is ThreadLocalRandomclass, which reduces number of instances of expensive-
to-create Random object in multi-threading environment.

Read More →