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

Let's 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 myValueis neither synchronizednor marked volatile. However, the only way to mutate it is to use the method update(). DZone replication on the Java concurrency core states that updates across all fields in a synchronized block are scanned by all threads. I was not sure if this meant only a synchronized object (lockObject) or any field (e.g. myValue).

Can anyone clarify this? Thank!

+3
source share
2 answers

, . , .

, , AtomicInteger:)

+8

:

  • Thread1, System.out.println(myValue); , myValue.

  • Thread2, System.out.println(myValue); Thread1 myValue, myValue, 1.

  • Thread1 myValue .

  • Thread2, System.out.println(myValue);, myValue Thread1.

0

All Articles