"Hi, Amigo!"

"There's this huge topic out there—the Java Memory Model. Basically, you don't have to know about it yet, but it will be helpful to hear about it."

"To eliminate all potential problems, Java changed its memory management mechanism. Now memory isn't simply divided into a thread's local cache and global memory—the mechanism is even better."

"And more complicated!"

"Yes, better and more complicated. It's like an airplane. Flying by plane is better than walking, but more complicated. I'll try to explain the new situation very simply."

"Here's what they came up with. A mechanism for synchronizing local thread memory, called 'happens-before', was added to the code. Several rules/conditions were invented. When these conditions are satisfied, memory is synchronized or updated to the current state.

"Here's an example:"

Order Thread 1 Thread 2


public int y = 1;
public int x = 1;

x = 2;
 y = 2;
The thread is waiting for the mutex to be released

 if (y == x)

"One of these conditions is the acquisition of the released mutex. If a mutex is released and re-acquired, then memory will be synchronized before the acquisition. Thread 2 will see the 'latest' values of the variables x and y, even if you don't declare them volatile."

"How interesting! And are there a lot of these conditions?"

"Enough—here are some conditions for synchronizing memory:"

  • "Within a single thread, any command happens-before any operation that follows it in the source code."
  • "The release of a lock happens-before the same lock is acquired."
  • "An exit from a synhronized block/method happens-before the synchronized block/method is entered on the same monitor."
  • "The writing of a volatile field to memory happens-before the same volatile field is read from memory."
  • "A end of a Thread object's run method happens-before the join() method ends or the isAlive() method returns false on the object in the same thread."
  • "A call to a Thread object's start() method happens-before the run() method starts on the object in the same thread."
  • "The end of the constructor happens-before the beginning of this class's finalize() method."
  • "A call to the interrupt() method happens-before the thread determines that this method has been called, either because an InterruptedException is thrown or by using the isInterrupted() or interrupted() methods."

"So, it's all a bit more complicated than I thought?"

"Yes, a bit more complicated…"

"Thank you, Rishi. I will think about it."

"Don't worry about this topic too much. The time will come when you'll understand it all on your own. For now, it would be better for you to understand the basics, rather than delve into the dense forest that is the internal workings of the Java machine. Java 9 will be released and then everything will change again."

"O_o. Yeah... Some things it is better to not know."