Introduction
Happens Before Relationship is one of the Java Memory Model Concept. It provides mechanism of ordering and visiblity between different operations in java concurrent applications. Simply saying, changes done by one thread will be visible to others.
The Happens-Before Relationship is a vital concept that ensures consistency and makes Java’s multi-threaded execution predictable.
Example (volatile)
Consider following class
class ReadWriteOperation {
int v = 0;
volatile boolean updated = false;
public writeThread(){
v = 1;
updated = true;
}
public readThread(){
if(updated){
System.out.println(v); // updated value of v
}
}
}
The implementation above demonstrates a happens-before relationship. All operations that occur before updated = true
are guaranteed to be visible to other threads. This ensures that when a read operation is performed, the updated value of v
will be retrieved.
Other Happens Before Operations
- Thread Start – all operation which were done before executing thread.start() instruction will be visible to that started thread.
- Thread Join – When Thread A will make join on Thread B, then it will see all updated values which happend in Thread B
- Thread Interruption – all operations done in main thread will be visible to worker thread on which interruption operation was executed.
- Locks – It guarantees that we release lock first, then we can aquire it.
Summary
Understanding the Happens-Before Relationship is crucial for building better and more reliable multi-threaded applications in Java. This knowledge ensures proper synchronization, data consistency, and thread-safe interactions, making your programs robust and dependable. Check more our articles !