One of the most critical aspects of a concurrent application is shared data. This has special importance in objects that extend the Thread class or implement the Runnable interface and in objects that are shared between two or more threads.
If you create an object of a class that implements the Runnable interface and then start various thread objects using the same Runnable object, all the threads would share the same attributes. This means that if you change an attribute in a thread, all the threads will be affected by this change.
Sometimes, you will be interested in having an attribute that won't be shared among all the threads that run the same object. The Java Concurrency API provides a clean mechanism called thread-local variables with very good performance. They have some disadvantages as well. They retain their value while the thread is alive. This can be problematic in situations where threads are reused.
In this recipe, we will develop two programs: one that would expose the problem in the first paragraph and another that would solve this problem using the thread-local variables mechanism.