Concurrency in Java: Interrupting and Joining Threads

  • 4.2/5
  • 3775
  • Jul 20, 2024

Interrupting a Thread

If any thread is in "sleeping" or "waiting" state, calling the interrupt() method on the thread, breaks out the sleeping or waiting state throwing "InterruptedException".

The thread is interrupted !!!

If the thread is not in the "sleeping" or "waiting" state, calling the interrupt() method performs normal behaviour and doesn't interrupt the thread but sets the interrupt flag to true.

In this scenario, we need to check for "isInterrupted()" and take the action accordingly, as shown in the example below:

The thread is interrupted !!!

Joining Threads

When we invoke the join() method on a thread, the calling thread goes into a waiting state. It remains in a waiting state until the referenced thread terminates.

Without join()

main: 0
Thread-0: 0
main: 1
main: 2
Thread-0: 1
main: 3
Thread-0: 2
main: 4
Thread-0: 3
Thread-0: 4

With join()

Thread-0: 0
Thread-0: 1
Thread-0: 2
Thread-0: 3
Thread-0: 4
main: 0
main: 1
main: 2
main: 3
main: 4

There are three overloaded join functions.

1) join()

It will put the current thread on wait until the thread on which it is called is dead. If thread is interrupted then it will throw InterruptedException.

2) join(long millis)

It will put the current thread on wait until the thread on which it is called is dead or specified time (milliseconds) is passes.

3) join(long millis, int nanos)

It will put the current thread on wait until the thread on which it is called is dead or specified time (milliseconds + nanos) is passes.

Index
Modern Java - What’s new in Java 9 to Java 17

32 min

What is differences between JDK, JVM and JRE ?

2 min

What is ClassLoader in Java ?

2 min

Object Oriented Programming (OOPs) Concept

17 min

Concurrency in Java: Creating and Starting a Thread

12 min

Concurrency in Java: Interrupting and Joining Threads

5 min

Concurrency in Java: Race condition, critical section, and atomic operations

13 min

Concurrency in Java: Reentrant, Read/Write and Stamped Locks

11 min

Concurrency in Java: "synchronized" and "volatile" keywords

10 min

Concurrency in Java: using wait(), notify() and notifyAll()

6 min

Concurrency in Java: What is "Semaphore" and its use?

2 min

Concurrency in Java: CompletableFuture and its use

18 min

Concurrency in Java: Producer-consumer problem using BlockingQueue

2 min

Concurrency in Java: Producer-Consumer Problem

2 min

Concurrency in Java: Thread pools, ExecutorService & Future

14 min

Java 8 Lambdas, Functional Interface & "static" and "default" methods

28 min

Method Reference in Java (Instance, Static, and Constructor Reference)

9 min

What’s new in Java 21: A Tour of its Most Exciting Features

14 min

Java Memory Leaks & Heap Dumps (Capturing & Analysis)

9 min

Memory footprint of the JVM (Heap & Non-Heap Memory)

15 min