Question

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();
    }

?

Was it helpful?

Solution

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.

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top