Domanda

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

?

È stato utile?

Soluzione

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.

Altri suggerimenti

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.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top