Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Impact of wait() method on a thread in synchronization block in java

synchronized (lockObject) {
  // update some value of the common shared resource
  lockObject.wait();
}

As on call of the wait() method, the thread will release the lock, I want to know after releasing the lock does it also update the value in the main memory of the shared resource object or it only updates the value after the execution of the synchronized block.

like image 496
Adarsh Verma Avatar asked Sep 16 '25 04:09

Adarsh Verma


1 Answers

It is a fallacy to think that due to synchronization (e.g. synchronized or volatile) data needs to be written to main memory. CPU caches on modern CPUs are always coherent due to the cache coherence protocol.

An object.wait causes the thread to release the lock. And as soon as another thread sends a notify, the lock is reacquired. The object.wait has no semantics in the Java memory model; only acquire and release of the lock are relevant.

So in your particular case, if a thread does a wait, it triggers a lock release. If another thread would read that state after acquiring the same lock, then there is a happens-before edge between the thread that did the release of the lock (due to wait) and the thread that acquired the lock. And therefore the second thread is guaranteed to see the changes of the first.

like image 154
pveentjer Avatar answered Sep 17 '25 18:09

pveentjer