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

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

Is there difference between :

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

and

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

?

有帮助吗?

解决方案

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.

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.

其他提示

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.

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

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top