什么是原子? [英] What is atomic?
问题描述
这是两个原子操作:
int value = 5;
Object obj = new Object();
但是当使用原语作为方法参数时,这是否被视为原子操作:<代码>public void setValue(int val, Object obj){
this.value = val;//原子?
this.obj = obj;//不是原子的?
}
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?
可以说对对象引用进行原子操作的唯一方法是将其声明为 null 或为其分配一个新对象,例如:
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;
和
Object obj = new Object();
?
推荐答案
如果上面方法中的参数是一个对象的引用,那么操作不会是原子的,对吧?
If the parameter in the above method was a reference to an object, then the operation would not be atomic, right?
总的来说,这是正确的.一个好的经验法则是考虑根本没有原子性,即使是像这样的原语:
In general this is correct. A good rule of thumb is to consider there is no atomicity at all, even with primitives like:
int b,c;
int a = ++b - c;
只有原语,但整个赋值是潜在的,不是原子的.
only primitives, but the whole assignment is potential not atomic.
如果您需要确保原子操作,您有不同的可能性:
If you need enshure atomic operations you have diferent posibilities:
- 同步块
- 不可变对象
- 特定库(java.util.concurrent.atomic)
这篇关于什么是原子?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!