i**p 发帖数: 902 | 1 【 以下文字转载自 Java 讨论区 】
发信人: isup (No), 信区: Java
标 题: Volatile variables do not provide any atomicity
发信站: BBS 未名空间站 (Sun Mar 8 14:38:43 2015, 美东)
This is from book "Core Java"
Volatile variables (private volatile boolean done;) do not provide any
atomicity. For example, the method
public void flipDone() { done = !done; } // not atomic
is not guaranteed to flip the value of the field.
What does "atomicity mean in this context? atomic for "=", for "!" or for
reading "done"? |
l******t 发帖数: 55733 | |
z****e 发帖数: 54598 | 3 不是早就有公论了么?
如果你不是很清楚地知道怎么实现一个jvm
那么该用synchronized时候就用synchronized
当然最理想的还是用vert.x这些
不要自己去搞automic这些
自己搞这些是很危险的,出了bugs连找都找不到 |
h*********8 发帖数: 404 | 4 use atomic package..already in jdk.. |
H****S 发帖数: 1359 | 5 你这个问题本身make sense吗?即便用AtomicBoolean,你觉得下面的程序一定可以
flip the value?
val b = new AtomicBoolean()
b.set(!b.get())
【在 i**p 的大作中提到】 : 【 以下文字转载自 Java 讨论区 】 : 发信人: isup (No), 信区: Java : 标 题: Volatile variables do not provide any atomicity : 发信站: BBS 未名空间站 (Sun Mar 8 14:38:43 2015, 美东) : This is from book "Core Java" : Volatile variables (private volatile boolean done;) do not provide any : atomicity. For example, the method : public void flipDone() { done = !done; } // not atomic : is not guaranteed to flip the value of the field. : What does "atomicity mean in this context? atomic for "=", for "!" or for
|
g*****g 发帖数: 34805 | 6 try
boolean v = b.get();
b.compareAndSet(v, !v);
The value is guaranteed to be !v right after last statement.
【在 H****S 的大作中提到】 : 你这个问题本身make sense吗?即便用AtomicBoolean,你觉得下面的程序一定可以 : flip the value? : val b = new AtomicBoolean() : b.set(!b.get())
|
m****o 发帖数: 182 | 7 volatile关键没有CAS,但是每次更新的结果都会直接被flush到main memory,所以多
线程赋值不需要synchronize。很多时候其实用volatile就够了。
[在 goodbug (好虫) 的大作中提到:]
:try
:
:........... |