[英]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
. 现在, myValue
既不synchronized
也不标记为volatile
。 However, the only way to mutate it is with the update()
method. 但是,改变它的唯一方法是使用update()
方法。 DZone's refcard on core java concurrency says that updates to fields in a syncronized block are seen by all threads. DZone对核心java并发性的refcard说,所有线程都可以看到同步块中字段的更新。 I was unsure if this meant the syncronized object only (lockObject) or any field (like myValue). 我不确定这是指仅同步对象(lockObject)还是任何字段(如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
:) 或者,如果您真的只有一个计数器,请使用AtomicInteger
:)
Consider: 考虑:
Thread1 executing System.out.println(myValue);
System.out.println(myValue);
执行System.out.println(myValue);
inside the synchronized block outputs the current value of myValue
. 在synchronized块内输出myValue
的当前值。
Thread2 executing System.out.println(myValue);
Thread2执行System.out.println(myValue);
before Thread1 increments myValue
will get the same value of myValue
as in step 1. 在 myValue
递增之前, myValue
将获得与步骤1中相同的myValue
值。
Thread1 increments myValue
inside the synchronized block. myValue
在synchronized块中增加myValue
。
Thread2 executing System.out.println(myValue);
Thread2执行System.out.println(myValue);
might get the new value of myValue
as set by Thread1. 可能会获得由myValue
设置的myValue
的新值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.