Java Memory Model and Happens Before? How does it Work?
What is Happens Before in Java memory model? How does it work?
Hello folks, a couple of days ago, one of my readers messaged me about a Java interview question he has recently faced - what is the happens-before relationship in Java concurrency? What is the benefit of it, and how exactly it works?
He kind of has some ideas about that its related to the Java Memory Model and provides some sort of visibility guaranteed but couldn't explain with conviction to his interviewer, particularly with a code example and was a bit disappointed.
He then asked me if I can write an article about it. I said you should have read the Java concurrency in Practice book or join the Java Concurrency in Practice Bundle course by Heinz Kabutz before the interview, that would have helped, but nonetheless, I liked the idea to just provide a quick overview of what is the happens-before relationship between threads in Java.
To understand the happens-before relationship, you need to first understand what would happen if the same variable is accessed by multiple threads? Particularly if one thread writes into the variable, and one thread read from it at the same time.
For example, let's say we have the following code, which is executed by Thread T1, (note, integer variable y is initialized before x)
int y = 1;
int x = 2;
Now, we have another piece of code which is executed by another thread T2 where the value of both the variable is printed (note variable x is printed before y) :
System.out.print(x);
System.out.println(y);
What do you think? What should be printed on the screen?
Keep reading with a 7-day free trial
Subscribe to Javarevisited Newsletter to keep reading this post and get 7 days of free access to the full post archives.