Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases now! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
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 FREE CHAPTER 2. Basic Thread Synchronization 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

Interrupting a thread

A Java program with more than one execution thread only finishes when the execution of all of its threads end (more specifically, when all its non-daemon threads end their execution or when one of the threads uses the System.exit() method). Sometimes, you may need to finish a thread because you want to terminate a program or when a user of the program wants to cancel the tasks that a thread object is doing.

Java provides an interruption mechanism that indicates to a thread that you want to finish it. One peculiarity of this mechanism is that thread objects have to check whether they have been interrupted or not, and they can decide whether they respond to the finalization request or not. A thread object can ignore it and continue with its execution.

In this recipe, we will develop a program that creates a thread and forces its finalization after 5 seconds, using the interruption mechanism.

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 PrimeGenerator that extends the Thread class:
        public class PrimeGenerator extends Thread{
  1. Override the run() method including a loop that will run indefinitely. In this loop, process consecutive numbers beginning from one. For each number, calculate whether it's a prime number; if yes, as in this case, write it to the console:
        @Override 
public void run() {
long number=1L;
while (true) {
if (isPrime(number)) {
System.out.printf("Number %d is Prime\n",number);
}
  1. After processing a number, check whether the thread has been interrupted by calling the isInterrupted() method. If this method returns true, the thread has been interrupted. In this case, we write a message in the console and end the execution of the thread:
            if (isInterrupted()) { 
System.out.printf("The Prime Generator has been
Interrupted");
return;
}
number++;
}
}
  1. Implement the isPrime() method. You can get its code from the Creating, running, and setting information of a thread recipe of this chapter.
  2. Now implement the main class of the example by implementing a class called Main and the main() method:
        public class Main { 
public static void main(String[] args) {
  1. Create and start an object of the PrimeGenerator class:
        Thread task=new PrimeGenerator(); 
task.start();
  1. Wait for 5 seconds and interrupt the PrimeGenerator thread:
        try { 
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
task.interrupt();
  1. Then, write information related to the status of the interrupted thread. The output of this piece of code will depend on whether the thread ends its execution before or after:
          System.out.printf("Main: Status of the Thread: %s\n",
task.getState());
System.out.printf("Main: isInterrupted: %s\n",
task.isInterrupted());
System.out.printf("Main: isAlive: %s\n", task.isAlive());
}
  1. Run the example and see the results.

How it works...

The following screenshot shows the result of the execution of the previous example. We can see how the PrimeGenerator thread writes the message and ends its execution when it detects that it has been interrupted. Refer to the following screenshot:

The Thread class has an attribute that stores a boolean value indicating whether the thread has been interrupted or not. When you call the interrupt() method of a thread, you set that attribute to true. The isInterrupted() method only returns the value of that attribute.

The main() method writes information about the status of the interrupted thread. In this case, as this code is executed before the thread has finished its execution, the status is RUNNABLE, the return value of the isInterrupted() method is true, and the return value of the isAlive() method is true as well. If the interrupted Thread finishes its execution before the execution of this block of code (you can, for example, sleep the main thread for a second), the methods isInterrupted() and isAlive() will return a false value.

There's more...

The Thread class has another method to check whether a thread has been interrupted or not. It's the static method, interrupted(), that checks whether the current thread has been interrupted or not.

There is an important difference between the isInterrupted() and interrupted() methods. The first one doesn't change the value of the interrupted attribute, but the second one sets it to false.

As mentioned earlier, a thread object can ignore its interruption, but this is not the expected behavior.

You have been reading a chapter from
Java 9 Concurrency Cookbook, Second Edition - Second Edition
Published in: Apr 2017
Publisher: Packt
ISBN-13: 9781787124417
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 $19.99/month. Cancel anytime