-
Book Overview & Buying
-
Table Of Contents
-
Feedback & Rating

Java 9 Concurrency Cookbook, Second Edition
By :

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.
The example for this recipe has been implemented using the Eclipse IDE. If you use Eclipse or a different IDE, such as NetBeans, open it and create a new Java project.
Follow these steps to implement the example:
UnsafeTask
and specify that it implements the Runnable
interface. Declare a private java.util.Date
attribute:public class UnsafeTask implements Runnable{ private Date startDate;
run()
method of the UnsafeTask
object. This method will initialize the startDate
attribute, write its value to the console, sleep for a random period of time, and again write the value of the startDate
attribute:@Override public void run() { startDate=new Date(); System.out.printf("Starting Thread: %s : %s\n", Thread.currentThread().getId(),startDate); try { TimeUnit.SECONDS.sleep( (int)Math.rint(Math.random()*10)); } catch (InterruptedException e) { e.printStackTrace(); } System.out.printf("Thread Finished: %s : %s\n", Thread.currentThread().getId(),startDate); }
Main
with a main()
method. This method will create an object of the UnsafeTask
class and start 10
threads using this object, sleeping for 2 seconds between each thread:public class Main { public static void main(String[] args) { UnsafeTask task=new UnsafeTask(); for (int i=0; i<10; i++){ Thread thread=new Thread(task); thread.start(); try { TimeUnit.SECONDS.sleep(2); } catch (InterruptedException e) { e.printStackTrace(); } } } }
SafeTask
and specify that it implements the Runnable
interface:public class SafeTask implements Runnable {
ThreadLocal<Date>
class. This object will have an implicit implementation that would include the initialValue()
method. This method will return the actual date:private static ThreadLocal<Date> startDate=new ThreadLocal<Date>(){ protected Date initialValue(){ return new Date(); } };
run()
method. It has the same functionality as the run()
method of UnsafeTask class
, but it changes the way it accesses the startDate
attribute. Now we will use the get()
method of the startDate
object:@Override public void run() { System.out.printf("Starting Thread: %s : %s\n", Thread.currentThread().getId(),startDate.get()); try { TimeUnit.SECONDS.sleep((int)Math.rint(Math.random()*10)); } catch (InterruptedException e) { e.printStackTrace(); } System.out.printf("Thread Finished: %s : %s\n", Thread.currentThread().getId(),startDate.get()); }
Main
class of this example is the same as the unsafe example. The only difference is that it changes the name of the Runnable
class.In the following screenshot, you can see the results of the execution of the safe sample. The ten Thread
objects have their own value of the startDate
attribute:
The thread-local variables mechanism stores a value of an attribute for each thread that uses one of these variables. You can read the value using the get()
method and change the value using the set()
method. The first time you access the value of a thread-local variable, if it has no value for the thread object that it is calling, the thread-local variable will call the initialValue()
method to assign a value for that thread and return the initial value.
The thread-local class also provides the remove()
method that deletes the value stored in a thread-local variable for the thread that it's calling.
The Java Concurrency API includes the InheritableThreadLocal
class that provides inheritance of values for threads created from a thread. If thread A
has a value in a thread-local variable and it creates another thread B
, then thread B
will have the same value as thread A
in the thread-local variable. You can override the childValue()
method that is called to initialize the value of the child thread in the thread-local variable. It receives the value of the parent thread as a parameter in the thread-local variable.