Back Thread Signaling in Java

20-30
Created By: Jakob Jenkov
Published At: 2022-10-25
Search Query: Java Threads
Tags: Java Java Concurrency Java Multithreading Java Thread Signaling Missed Signals Spurious Wakeups
Java has a set of thread signaling features that enable one Java thread to coordinate its actions with another. These basic thread signaling features are provided via the Object class wait() , notify() and notifyAll() methods.

When implementing thread signaling in Java you need to be aware of the problem of missed signals and spurious wakeups. I cover both in this video too.

Chapters:
0:00 Java Thread signaling introduction - wait(), notify() and notifyAll()
1:50 Calling wait(), notify() or notifyAll() must be done from within a synchronized block
2:31 Calling wait() releases the synchronization lock
5:50 Designing a thread signaling class in Java
9:17 Missed signals
17:24 notify() vs. notifyAll()
19:24 Spurious wakeups

Java Thread Signaling - text:
https://jenkov.com/tutorials/java-concurrency/thread-signaling.html

Java Concurrency - text:
https://jenkov.com/tutorials/java-concurrency/thread-signaling.html

Java Concurrency - playlist:
https://www.youtube.com/playlist?list=PLL8woMHwr36EDxjUoCzboZjedsnhLP1j4
logo Ask VidTutorAssistant
Comment
or
Question
Your name
Comments with generated responses
@rm6267
2022-10-26

In this case 12:47 it's not necessary to used atomic type in signalRaised because is synchronized all the class with synchronized(this) {}?

@JakobJenkov

Inside a synchronized block you do not need to use atomic types, nor volatile variables. However, then all access to these variables (fields) should be within synchronized blocks.

VidTutorAssistant (GPT-4)

Good observation @rm6267! In the context of the SignalCarrier class that was discussed, you're right in saying that the use of 'synchronized(this)' enforces mutual exclusivity ensuring that any thread that's executing the enclosed code block holds the lock on the 'this' object and, as a result, prevents other threads from accessing it simultaneously.

However, it's important to understand that the usage of atomic types like AtomicBoolean, is used here for its 'visibility' property rather than concurrency. It ensures that when its value is updated by one thread, the updated value is immediately visible to other threads. Despite the synchronized block, there can still be visibility issues between separate locks unless there's a "happens-before" relation, and usage of volatile variables (as in the atomic types) provide such a relation.

But in terms of only synchronization, you're correct; 'synchronized(this)' would suffice. If we don't consider the visibility aspect, we don't necessarily need the signalRaised to be an AtomicBoolean. I hope this explains it! Feel free to reach out if you have any more questions. Happy learning!