Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Concurrency spec ?: Is an update to a field inside a synchronized block visible to all threads?

Say you have this code:

private Object lockObject = new Object();
private Integer myValue = new Integer(0);

public void update(){
 synchronized(lockObject){
  System.out.println(myValue);
  myValue++;
 }
}

Now, myValue is neither synchronized on nor is it marked volatile. However, the only way to mutate it is with the update() method. DZone's refcard on core java concurrency says that updates to fields in a syncronized block are seen by all threads. I was unsure if this meant the syncronized object only (lockObject) or any field (like myValue).

Can anyone elaborate on this? Thanks!

like image 657
Jonathan S. Fisher Avatar asked Nov 20 '25 03:11

Jonathan S. Fisher


1 Answers

All field updates within the synchronized block are guaranteed to be visible to other threads so long as they also synchronize on the same object before reading. So long as you synchronize all access to the shared mutable state, you should see all the updates.

Alternatively, if you really only have a counter, use AtomicInteger :)

like image 136
Jon Skeet Avatar answered Nov 21 '25 18:11

Jon Skeet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!