什么是原子?
这是两个原子操作:
int value = 5;
Object obj = new Object();
但是当使用原语作为方法参数时,这是否会被视为原子操作: <代码> 公共无效 setValue(int val, 对象 obj){
this.value = val; // 原子?
这个.obj = obj; // 不是原子的?
}
? 对象引用的副本不是原子的,因为它包括读取和写入,对吧?
)是否正确
Object obj = null;
说对对象引用进行原子操作的唯一方法是将其声明为 null 或为其分配一个新对象(例如:和
Object obj = new Object();
?
These are two atomic operations:
int value = 5;
Object obj = new Object();
But when using a primitive as a method parameter, would this be considered as an atomic operation:
public void setValue(int val, Object obj){
this.value = val; // Atomic?
this.obj = obj; // Not atomic?
}
?
The copy of the object reference is not atomic since it includes a read and a write, right?
Would it be correct to say that the only way to make an atomic operation on an object reference is to declare it null or assign a new object to it, like:
Object obj = null;
and
Object obj = new Object();
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
一般来说,这是正确的。一个好的经验法则是考虑根本不存在原子性,即使对于这样的原语也是如此:
只有原语,但整个分配可能不是原子性的。
如果您需要确保原子操作,您有不同的可能性:
In general this is correct. A good rule of thumb is to consider there is no atomicity at all, even with primitives like:
only primitives, but the whole assignment is potential not atomic.
If you need enshure atomic operations you have diferent posibilities:
当线程读取原语(long 和 double 除外)或对象引用的值时,它会看到自己在此变量中设置的值,或另一个线程在此变量中设置的值。
然而,尽管在一个线程中为共享变量赋值是原子的,但这并不意味着所有其他线程都会立即看到新值。为此,该变量应声明为 volatile。易失性还使写入长和双原子。不过,在这种情况下,我更喜欢使用 AtomicXxx(AtomicLong、AtomicBoolean 等)。
如果您想以原子方式更改两个共享变量的值,那么您应该使用唯一锁同步对这些变量的每次访问(读取和写入)。
此外,每个“检查然后执行”或“读取然后写入”操作都是非原子的。这意味着这些操作也需要同步:
问题中的每个操作都是原子的。但在
setValue()
中,您有两个原子操作。整个setValue
调用不是原子的。When a thread reads the value of a primitive (except long and double), or of an object reference, it sees the value it has set in this variable, or the value that another thread has set in this variable.
However, although assigning a value to a shared variable in one thread is atomic, this doesn't mean that all the other threads will see the new value right after. To do that, the variable should be declared volatile. volatile also makes writes to long and double atomic. I prefer using AtomicXxx (AtomicLong, AtomicBoolean, etc.) in this case, though.
And if you want to atomically change the values of two shared variables, then you should synchronize every access (read and write) to these variables using a unique lock.
Moreover, every "check then act" or "read then write" operation is non-atomic. This means that these operations need synchronization as well:
Every single operation in your question is atomic. But in
setValue()
, you have two atomic operations. The wholesetValue
call is not atomic.致 JLS!
所以分配是原子的。
To the JLS!
So the assignment is atomic.
现在整个函数是“原子的”,我还没有看到 Java 中使用过这个术语
now the entire function is "atomic" which term I have not seen used in Java