Take a look on the following piece of code:
private int var; public synchronized void changeVar() { var++; }
Using the synchronized block we define that
the var is available only for a thread which captures the monitor/lock of the
synchronized block. For example, thread-A changes the value of var and leaves
the block (releases monitor), after that thread-B captures the monitor and
modifies the value of var changed by thread-A, var gets value 2. That’s a
normal and expected behavior, but sometimes we need to have our variables with thread
visibility scope.
What I mean is having var independently
modified by thread-A and thread-B, if the thread-A calls changeVar method 10
times then var will have value 10 only for thread-A, thread-B may have var
equals 0 if the thread has not call changeVar method; to do that we may use
ThreadLocal (http://docs.oracle.com/javase/7/docs/api/java/lang/ThreadLocal.html)
instance.


