同步块中的操作是否对其他线程可见?
Are actions in a synchronized block visible to other threads?
我已经阅读了这个Related Question,答案很有帮助,但还有一个问题。
我听说同步块中共享字段的更改保证对其他线程可见。
对于这样的代码:
线程 1:
synchronized(lock) {
obj.field1 = value1;
}
线程 2:
synchronized(lock) {
System.out.println(obj.field1);
}
假设thread1先于thread2,据说按照Java规范,可能是这样的:
hb(write to obj.field1 in threadOne, unlock in threadOne) AND
hb(unlock in threadOne, lock in threadTwo) AND
hb(lock in threadTwo, read from obj.field in threadTwo)
hb在Java规范中代表happens-before,它保证了可见性。
并且因为“如果 hb(x, y) 和 hb(y, z),则 hb(x, z)”,我们得到:
hb(write to obj.field1 in threadOne, read from obj.field1 in threadTwo)
我的问题在第一行:
hb(write to obj.field1 in threadOne, unlock in threadOne)
在Java规范中,我只找到:
An unlock action on monitor m synchronizes-with all subsequent lock
actions on m (where "subsequent" is defined according to the
synchronization order).
表示解锁操作发生在后续锁定操作之前。但我找不到像这样的词:
An action in synchronized block happens-before the unlock action.
所以它是正确的吗?我在哪里可以找到它?
同一个线程的所有操作都按发生前关系排序。
JLS 17.4.5:
If x and y are actions of the same thread and x comes before y in program order, then hb(x, y).
另请注意,happens-before 是可传递的,因此如果同步块中的写入发生在解锁之前,并且解锁发生在另一个线程的锁定之前,那么写入发生在同步块中的任何操作之前其他线程。
这里最好的解释是解锁动作与线程中的最后一个动作有先行边。这称为程序顺序。
它在 documentation
中有描述
Among all the inter-thread actions performed by each thread t, the program order of t is a total order that reflects the order in which these actions would be performed according to the intra-thread semantics of t.
我已经阅读了这个Related Question,答案很有帮助,但还有一个问题。
我听说同步块中共享字段的更改保证对其他线程可见。
对于这样的代码:
线程 1:
synchronized(lock) {
obj.field1 = value1;
}
线程 2:
synchronized(lock) {
System.out.println(obj.field1);
}
假设thread1先于thread2,据说按照Java规范,可能是这样的:
hb(write to obj.field1 in threadOne, unlock in threadOne) AND
hb(unlock in threadOne, lock in threadTwo) AND
hb(lock in threadTwo, read from obj.field in threadTwo)
hb在Java规范中代表happens-before,它保证了可见性。
并且因为“如果 hb(x, y) 和 hb(y, z),则 hb(x, z)”,我们得到:
hb(write to obj.field1 in threadOne, read from obj.field1 in threadTwo)
我的问题在第一行:
hb(write to obj.field1 in threadOne, unlock in threadOne)
在Java规范中,我只找到:
An unlock action on monitor m synchronizes-with all subsequent lock actions on m (where "subsequent" is defined according to the synchronization order).
表示解锁操作发生在后续锁定操作之前。但我找不到像这样的词:
An action in synchronized block happens-before the unlock action.
所以它是正确的吗?我在哪里可以找到它?
同一个线程的所有操作都按发生前关系排序。
JLS 17.4.5:
If x and y are actions of the same thread and x comes before y in program order, then hb(x, y).
另请注意,happens-before 是可传递的,因此如果同步块中的写入发生在解锁之前,并且解锁发生在另一个线程的锁定之前,那么写入发生在同步块中的任何操作之前其他线程。
这里最好的解释是解锁动作与线程中的最后一个动作有先行边。这称为程序顺序。 它在 documentation
中有描述Among all the inter-thread actions performed by each thread t, the program order of t is a total order that reflects the order in which these actions would be performed according to the intra-thread semantics of t.