Search icon CANCEL
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Java 9 Concurrency Cookbook, Second Edition

You're reading from   Java 9 Concurrency Cookbook, Second Edition Build highly scalable, robust, and concurrent applications

Arrow left icon
Product type Paperback
Published in Apr 2017
Publisher Packt
ISBN-13 9781787124417
Length 594 pages
Edition 2nd Edition
Languages
Concepts
Arrow right icon
Author (1):
Arrow left icon
Javier Fernández González Javier Fernández González
Author Profile Icon Javier Fernández González
Javier Fernández González
Arrow right icon
View More author details
Toc

Table of Contents (12) Chapters Close

Preface 1. Thread Management 2. Basic Thread Synchronization FREE CHAPTER 3. Thread Synchronization Utilities 4. Thread Executors 5. Fork/Join Framework 6. Parallel and Reactive Streams 7. Concurrent Collections 8. Customizing Concurrency Classes 9. Testing Concurrent Applications 10. Additional Information 11. Concurrent Programming Design

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.

lock icon The rest of the chapter is locked
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at R$50/month. Cancel anytime