How to do it...

Follow these steps to implement the example:

  1. First, implement a program that has the problem exposed previously. Create a class called UnsafeTask and specify that it implements the Runnable interface. Declare a private java.util.Date attribute:
        public class UnsafeTask implements Runnable{           private Date startDate;
  1. Implement the 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)); ...

Get Java 9 Concurrency Cookbook - Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.