Book Image

Java 9 Concurrency Cookbook, Second Edition - Second Edition

By : Javier Fernández González
Book Image

Java 9 Concurrency Cookbook, Second Edition - Second Edition

By: Javier Fernández González

Overview of this book

Writing concurrent and parallel programming applications is an integral skill for any Java programmer. Java 9 comes with a host of fantastic features, including significant performance improvements and new APIs. This book will take you through all the new APIs, showing you how to build parallel and multi-threaded applications. The book covers all the elements of the Java Concurrency API, with essential recipes that will help you take advantage of the exciting new capabilities. You will learn how to use parallel and reactive streams to process massive data sets. Next, you will move on to create streams and use all their intermediate and terminal operations to process big collections of data in a parallel and functional way. Further, you’ll discover a whole range of recipes for almost everything, such as thread management, synchronization, executors, parallel and reactive streams, and many more. At the end of the book, you will learn how to obtain information about the status of some of the most useful components of the Java Concurrency API and how to test concurrent applications using different tools.
Table of Contents (12 chapters)

Sleeping and resuming a thread

Sometimes, you may be interested in pausing the execution of a thread during a determined period of time. For example, a thread in a program checks the sensor state once per minute. The rest of the time, it does nothing. During this time, the thread doesn't use any resources of the computer. After this period is over, the thread will be ready to continue with its execution when the operating system scheduler chooses it to be executed. You can use the sleep() method of the Thread class for this purpose. This method receives a long number as a parameter that indicates the number of milliseconds during which the thread will suspend its execution. After that time, the thread continues with its execution in the next instruction to the sleep() one when the JVM assigns it CPU time.

Another possibility is to use the sleep() method of an element of the TimeUnit enumeration. This method uses the sleep() method of the Thread class to put the current thread to sleep, but it receives the parameter in the unit that it represents and converts it into milliseconds.

In this recipe, we will develop a program that uses the sleep() method to write the actual date every second.

Getting ready

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.

How to do it...

Follow these steps to implement the example:

  1. Create a class called ConsoleClock and specify that it implements the Runnable interface:
        public class ConsoleClock implements Runnable {
  1. Implement the run() method:
        @Override 
public void run() {
  1. Write a loop with 10 iterations. In each iteration, create a Date object, write it to the console, and call the sleep() method of the SECONDS attribute of the TimeUnit class to suspend the execution of the thread for 1 second. With this value, the thread will be sleeping for approximately 1 second. As the sleep() method can throw an InterruptedException exception, we have to include some code to catch it. It's good practice to include code that frees or closes the resources the thread is using when it's interrupted:
          for (int i = 0; i < 10; i++) { 
System.out.printf("%s\n", new Date());
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
System.out.printf("The FileClock has been interrupted");
}
}
}
  1. We have implemented the thread. Now let's implement the main class of the example. Create a class called Main that contains the main() method:
        public class Main { 
public static void main(String[] args) {
  1. Create an object of the FileClock class and a thread to execute it. Then, start executing a thread:
        FileClock clock=new FileClock(); 
Thread thread=new Thread(clock);
thread.start();
  1. Call the sleep() method of the SECONDS attribute of the TimeUnit class in the main thread to wait for 5 seconds:
        try { 
TimeUnit.SECONDS.sleep(5);
} catch (InterruptedException e) {
e.printStackTrace();
};
  1. Interrupt the FileClock thread:
        thread.interrupt();
  1. Run the example and see the results.

How it works...

When you run the example, you would see how the program writes a Date object per second and also the message indicating that the FileClock thread has been interrupted.

When you call the sleep() method, the thread leaves the CPU and stops its execution for a period of time. During this time, it's not consuming CPU time, so the CPU could be executing other tasks.

When the thread is sleeping and is interrupted, the method throws an InterruptedException exception immediately and doesn't wait until the sleeping time is finished.

There's more...

The Java concurrency API has another method that makes a thread object leave the CPU. It's the yield() method, which indicates to the JVM that the thread object can leave the CPU for other tasks. The JVM does not guarantee that it will comply with this request. Normally, it's only used for debugging purposes.