挥发性和原子性在一起它有意义吗?

时间:2023-01-06 19:22:55

I noticed that all examples about atomic writes without volatile keyword. Surely it is right.

我注意到所有关于没有volatile关键字的原子写入的例子。当然是对的。

What will happen if I add the volatile modifier to my atomic link ?

如果我将volatile修饰符添加到原子链接会发生什么?

Is there difference between :

有没有区别:

public class VolatilAtomic {
    volatile AtomicInteger atomicInteger = new AtomicInteger();
}

and

 public class VolatilAtomic {
         AtomicInteger atomicInteger = new AtomicInteger();
    }

?

3 个解决方案

#1


4  

There would be a difference if you reassign the variable: atomicInteger = new AtomicInteger() in a method, in which case marking the variable as volatile will guarantee that the assignment will be visible by other threads.

如果在方法中重新分配变量:atomicInteger = new AtomicInteger()会有所不同,在这种情况下将变量标记为volatile将保证其他线程可以看到赋值。

But if you only use the AtomicInteger instance that is created with each instance of your class and never reassign it, then volatile is unnecessary.

但是,如果您只使用使用类的每个实例创建的AtomicInteger实例并且从不重新分配它,那么volatile是不必要的。

#2


4  

Generally speaking, final would be more appropriate.

一般来说,最终会更合适。

The important thing about modifiers is that the alter the reference, not the object referenced. e.g.

修饰符的重要之处在于改变引用,而不是引用的对象。例如

final int[] a = { 0 };
a[0] = 5;    // ok, not final
a = b;       // not ok as it is final 

similarly

同样

volatile int[] a = { 0 };
a[0] = 5;    // not a volatile write
a = b;       // volatile write.

#3


0  

Both provide the same visibility, but only AtomicInteger provide atomicity.

两者都提供相同的可见性,但只有AtomicInteger提供原子性。

#1


4  

There would be a difference if you reassign the variable: atomicInteger = new AtomicInteger() in a method, in which case marking the variable as volatile will guarantee that the assignment will be visible by other threads.

如果在方法中重新分配变量:atomicInteger = new AtomicInteger()会有所不同,在这种情况下将变量标记为volatile将保证其他线程可以看到赋值。

But if you only use the AtomicInteger instance that is created with each instance of your class and never reassign it, then volatile is unnecessary.

但是,如果您只使用使用类的每个实例创建的AtomicInteger实例并且从不重新分配它,那么volatile是不必要的。

#2


4  

Generally speaking, final would be more appropriate.

一般来说,最终会更合适。

The important thing about modifiers is that the alter the reference, not the object referenced. e.g.

修饰符的重要之处在于改变引用,而不是引用的对象。例如

final int[] a = { 0 };
a[0] = 5;    // ok, not final
a = b;       // not ok as it is final 

similarly

同样

volatile int[] a = { 0 };
a[0] = 5;    // not a volatile write
a = b;       // volatile write.

#3


0  

Both provide the same visibility, but only AtomicInteger provide atomicity.

两者都提供相同的可见性,但只有AtomicInteger提供原子性。