Volatile piggyback. Is this enough for visiblity?(易变的背负式.这足以可见性吗?)
问题描述
This is about volatile piggyback. Purpose: I want to reach a lightweight vars visibilty. Consistency of a_b_c is not important. I have a bunch of vars and I don't want to make them all volatile.
Is this code threadsafe?
class A {
public int a, b, c;
volatile int sync;
public void setup() {
a = 2;
b = 3;
c = 4;
}
public void sync() {
sync++;
}
}
final static A aaa = new A();
Thread0:
aaa.setup();
end
Thread1:
for(;;) {aaa.sync(); logic with aaa.a, aaa.b, aaa.c}
Thread2:
for(;;) {aaa.sync(); logic with aaa.a, aaa.b, aaa.c}
Java Memory Model defines the happens-before relationship which has the following properties (amongst others):
- "Each action in a thread happens-before every action in that thread that comes later in the program order" (program order rule)
- "A write to a volatile field happens-before every subsequent read of that same volatile" (volatile variable rule)
These two properties together with transitivity of the happens-before relationship imply the visibility guarantees that OP seeks in the following manner:
- A write to
a
in thread 1 happens-before a write tosync
in a call tosync()
in thread 1 (program order rule). - The write to
sync
in the call tosync()
in thread 1 happens-before a read tosync
in a call tosync
in thread 2 (volatile variable rule). - The read from
sync
in the call tosync()
in thread 2 happens-before a read froma
in thread 2 (program order rule).
This implies that the answer to the question is yes, i.e. the call to sync()
in each iteration in threads 1 and 2 ensures visibility of changes to a
, b
and c
to the other thread(s). Note that this ensures visibility only. No mutual exclusion guarantees exist and hence all invariants binding a
, b
and c
may be violated.
See also Java theory and practice: Fixing the Java Memory Model, Part 2. In particular the section "New guarantees for volatile" which says
Under the new memory model, when thread A writes to a volatile variable V, and thread B reads from V, any variable values that were visible to A at the time that V was written are guaranteed now to be visible to B.
这篇关于易变的背负式.这足以可见性吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:易变的背负式.这足以可见性吗?
基础教程推荐
- 由于对所需库 rt.jar 的限制,对类的访问限制? 2022-01-01
- 如何对 HashSet 进行排序? 2022-01-01
- 如何使用 Stream 在集合中拆分奇数和偶数以及两者的总和 2022-01-01
- Spring Boot Freemarker从2.2.0升级失败 2022-01-01
- 如何强制对超级方法进行多态调用? 2022-01-01
- 在螺旋中写一个字符串 2022-01-01
- 如何使用 Eclipse 检查调试符号状态? 2022-01-01
- 如何在不安装整个 WTP 包的情况下将 Tomcat 8 添加到 Eclipse Kepler 2022-01-01
- Java 中保存最后 N 个元素的大小受限队列 2022-01-01
- 首次使用 Hadoop,MapReduce Job 不运行 Reduce Phase 2022-01-01