Sitemap

Thread Synchronization and ThreadLocal in Java

4 min readMay 30, 2020

--

Press enter or click to view image in full size

In this post we are going to see examples of thread joining, thread synchronization using object’s wait, notify and notifyAll methods and what is ThreadLocal and how to use it.

If you are more interested in Race Condition and Deadlock situations, take a look at my previous post (Threads in Java).

Thread Joining, join() method

The join() method puts the calling thread into a waiting state until the referenced thread terminates. It means that the join() method makes one thread wait until another thread completes its execution. If any thread calls an interrupt of the referenced thread, InterruptException exception will be thrown.

Method signatures

Waits forever for the thread to die.

public final void join() throws InterruptedException

Waits at most millis for the thread to die. A timeout of 0 millis means to wait forever (same as join() method).

public final synchronized void join(long millis) throws InterruptedException

Same as join(millis) except it waits at most millis + nanos for thread to die.

public final synchronized void join(long millis, int nanos) throws InterruptedException

Let’s see example of thread joining:

public static void main(String[] args) throws InterruptedException {
Worker worker1 = new Worker();
Worker worker2 = new Worker();

worker1.start();
worker1.join();

worker2.start();
worker2.join();
worker1.wait();

System.out.println("the main thread continues execution...");
}

public static class Worker extends Thread {

@Override
public void run() {
for (int i = 0; i < 4; i++) {
System.out.println("Thread: " + getName() + ", i[" + i + "]");
}
}
}

Console Output:

Thread: Thread-0, i[0] Thread: Thread-0, i[1]
Thread: Thread-0, i[2] Thread: Thread-0, i[3]
Thread: Thread-1, i[0] Thread: Thread-1, i[1]
Thread: Thread-1, i[2] Thread: Thread-1, i[3]
the main thread continues execution...

From the console output above you can see that Thread-0 started and finished iteration, after that Thread-1 started and finished iteration and at the end the main thread continued executing.

Object wait(), notify() and notifyAll() method

Every Object in Java has wait, notify and notifyAll methods, those methods are an important mechanism of thread synchronization. Calling the wait method puts the current thread to wait state until another thread invokes notify or notifyAll.

Get Milan Adamovic’s stories in your inbox

Join Medium for free to get updates from this writer.

The notify method wakes up a single random thread that is waiting for the object's monitor, while on the other hand notifyAll wakes up all threads that are waiting for the object's monitor.

Also there are two exceptions that might occur. The first one is InterruptedException which is thrown if any thread interrupts before or while the referenced thread is waiting. The second exception is IllegalMonitorStateException which is thrown if the referenced thread does not hold the object's monitor.

Let’s see an example of Sender and Receiver

public static void main(String[] args) {
List<Signal> signalBuffer = new ArrayList<>();

Thread senderThread = new Thread(new Sender(signalBuffer));
Thread receiverThread = new Thread(new Receiver(signalBuffer));

senderThread.start();
receiverThread.start();
}

public static class Sender implements Runnable {
private final List<Signal> buffer;

public Sender(List<Signal> buffer) {
this.buffer = buffer;
}

@Override
public void run() {
synchronized (buffer) {
while (!buffer.isEmpty()) {
try {
buffer.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}

for (int i = 0; i < 8; i++) {
Signal signal = new Signal();
signal.signalName = "Signal-" + i;
signal.value = i;

buffer.add(signal);
}

buffer.notifyAll();
}
}
}

public static class Receiver implements Runnable {
private final List<Signal> buffer;

public Receiver(List<Signal> buffer) {
this.buffer = buffer;
}

@Override
public void run() {
synchronized (buffer) {
while (buffer.isEmpty()) {
try {
buffer.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}

for (Signal signal : buffer) {
System.out.println("Receiver: " + signal);
}

buffer.clear();
buffer.notifyAll();
}
}
}

public static class Signal {
String signalName;
int value;

@Override
public String toString() {
return "Signal{" +
"signalName='" + signalName + '\'' +
", value=" + value +
'}';
}
}

Console Output:

Receiver: Signal{signalName='Signal-0', value=0} 
Receiver: Signal{signalName='Signal-1', value=1}
Receiver: Signal{signalName='Signal-2', value=2}
Receiver: Signal{signalName='Signal-3', value=3}
Receiver: Signal{signalName='Signal-4', value=4}
Receiver: Signal{signalName='Signal-5', value=5}
Receiver: Signal{signalName='Signal-6', value=6}
Receiver: Signal{signalName='Signal-7', value=7}

In the example above we have Sender and Receiver classes which implements a Runnable interface. Those two classes are run in separate threads called senderThread and receiverThread. For synchronization we use an instance of ArrayList.

If the signal buffer is empty, the Sender generates signals, puts them in a buffer and notifies the Receiver thread. Once the buffer is not empty and the Receiver thread is woken up, the Receiver thread will consume all signals and notify Sender.

If we put Sender’s and Receiver’s run method in while(true), these two threads will continue to produce and consume signals indefinitely.

What is ThreadLocal

ThreadLocal provides thread-local variables, meaning each thread has its own, independent initialized copy of the variable. ThreadLocal instances are typically private static fields that wish to associate state with a thread.

Let’s see example of ThreadLocal

public static void main(String[] args) {
ThreadIdentifier threadIdentifier = new ThreadIdentifier();

Runnable runnable = () -> {
for (int i = 0; i < 4; i++) {
String identifier = Thread.currentThread().getName();
if (identifier.equals(threadIdentifier.getIdentifier())) {
System.out.println("already set: " + identifier);
} else {
System.out.println("set thread identifier: " + identifier);
threadIdentifier.setIdentifier();
}

try {
Thread.sleep(1_000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};

Thread firstThread = new Thread(runnable, "first-thread");
Thread secondThread = new Thread(runnable, "second-thread");

firstThread.start();
secondThread.start();
}

public static class ThreadIdentifier {
private static final ThreadLocal<String> threadIdentifier = new ThreadLocal<>();

public void setIdentifier() {
threadIdentifier.set(Thread.currentThread().getName());
}

public String getIdentifier() {
return threadIdentifier.get();
}
}

Console Output:

set thread identifier: first-thread 
set thread identifier: second-thread
already set: second-thread
already set: first-thread
already set: second-thread
already set: first-thread
already set: first-thread
already set: second-thread

As we can see in the example above, we have a private static final ThreadLocal variable of type String associated with its thread. Once the thread is terminated, all of its copies of thread-local instances are subject to garbage collection.

Originally published at https://dev4.dev on May 30, 2020.

--

--