Sign In Start Free Trial
Account

Add to playlist

Create a Playlist

Modal Close icon
You need to login to use this feature.
  • Book Overview & Buying Java 9 Concurrency Cookbook, Second Edition
  • Table Of Contents Toc
  • Feedback & Rating feedback
Java 9 Concurrency Cookbook, Second Edition

Java 9 Concurrency Cookbook, Second Edition

By : Javier Fernández González
4 (1)
close
close
Java 9 Concurrency Cookbook, Second Edition

Java 9 Concurrency Cookbook, Second Edition

4 (1)
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 (19 chapters)
close
close
Title Page
Credits
About the Author
About the Reviewer
www.PacktPub.com
Customer Feedback
Dedication
Preface

Waiting for the finalization of a thread


In some situations, we will have to wait for the end of the execution of a thread (the run() method ends its execution). For example, we may have a program that will begin initializing the resources it needs before proceeding with the rest of the execution. We can run initialization tasks as threads and wait for their finalization before continuing with the rest of the program.

For this purpose, we can use the join() method of the Thread class. When we call this method using a thread object, it suspends the execution of the calling thread until the object that is called finishes its execution.

In this recipe, we will learn the use of this method with an initialization example.

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 DataSourcesLoader and specify that it implements the Runnable interface:
        public class DataSourcesLoader implements Runnable {
  1. Implement the run() method. It writes a message to indicate that it starts its execution, sleeps for 4 seconds, and writes another message to indicate that it ends its execution:
        @Override 
        public void run() { 
          System.out.printf("Beginning data sources loading: %s\n",
                            new Date()); 
          try { 
            TimeUnit.SECONDS.sleep(4); 
          } catch (InterruptedException e) { 
            e.printStackTrace(); 
          } 
          

 

          System.out.printf("Data sources loading has finished: %s\n",
                            new Date()); 
        }
  1. Create a class called NetworkConnectionsLoader and specify that it implements the Runnable interface. Implement the run() method. It will be equal to the run() method of the DataSourcesLoader class, but it will sleep for 6 seconds.
  2. Now, 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 DataSourcesLoader class and a thread to run it:
       DataSourcesLoader dsLoader = new DataSourcesLoader(); 
       Thread thread1 = new Thread(dsLoader,"DataSourceThread");
  1. Create an object of the NetworkConnectionsLoader class and a thread to run it:
        NetworkConnectionsLoader ncLoader = new NetworkConnectionsLoader(); 
        Thread thread2 = new Thread(ncLoader,"NetworkConnectionLoader");
  1. Call the start() method of both the thread objects:
        thread1.start(); 
        thread2.start();
  1. Wait for the finalization of both the threads using the join() method. This method can throw an InterruptedException exception, so we have to include the code to catch it:
       try { 
          thread1.join(); 
          thread2.join(); 
        } catch (InterruptedException e) { 
          e.printStackTrace(); 
        }
  1. Write a message to indicate the end of the program:
        System.out.printf("Main: Configuration has been loaded: %s\n",
                          new Date());
  1. Run the program and see the results.

How it works...

When you run this program, you would understand how both the thread objects start their execution. First, the DataSourcesLoader thread finishes its execution. Then, the NetworkConnectionsLoader class finishes its execution. At this moment, the main thread object continues its execution and writes the final message.

There's more...

Java provides two additional forms of the join() method:

  • join (long milliseconds)
  • join (long milliseconds, long nanos)

In the first version of the join() method, instead of indefinitely waiting for the finalization of the thread called, the calling thread waits for the milliseconds specified as the parameter of the method. For example, if the object thread1 has thread2.join(1000), thread1 suspends its execution until one of these two conditions are met:

  • thread2 has finished its execution
  • 1,000 milliseconds have passed

When one of these two conditions is true, the join() method returns. You can check the status of the thread to know whether the join() method was returned because it finished its execution or because the specified time had passed.

The second version of the join() method is similar to the first one, but it receives the number of milliseconds and nanoseconds as parameters.

notes
bookmark Notes and Bookmarks search Search in title playlist Add to playlist download Download options font-size Font size

Change the font size

margin-width Margin width

Change margin width

day-mode Day/Sepia/Night Modes

Change background colour

Close icon Search
Country selected

Close icon Your notes and bookmarks

Confirmation

Modal Close icon
claim successful

Buy this book with your credits?

Modal Close icon
Are you sure you want to buy this book with one of your credits?
Close
YES, BUY

Submit Your Feedback

Modal Close icon

Create a Note

Modal Close icon
You need to login to use this feature.

Delete Bookmark

Modal Close icon
Are you sure you want to delete it?
Cancel
Yes, Delete

Delete Note

Modal Close icon
Are you sure you want to delete it?
Cancel
Yes, Delete

Edit Note

Modal Close icon
Write a note (max 255 characters)
Cancel
Update Note