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!
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 :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With