Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between using a volatile primitive over atomic variables? [duplicate]

Possible Duplicate:
Java: volatile boolean vs AtomicBoolean

When is it appropriate to use a volatile primitive (e.g. boolean, integer or long) instead of AtomicBoolean, AtomicInteger or AtomicLong, and vice-versa?

like image 463
David Grant Avatar asked Oct 12 '12 12:10

David Grant


People also ask

What is difference between volatile and atomic variables Java?

Volatile and Atomic are two different concepts. Volatile ensures, that a certain, expected (memory) state is true across different threads, while Atomics ensure that operation on variables are performed atomically.

What is the difference between atomic volatile synchronized?

Synchronized Vs Atomic Vs Volatile:Volatile and Atomic is apply only on variable , While Synchronized apply on method. Volatile ensure about visibility not atomicity/consistency of object , While other both ensure about visibility and atomicity.

Are atomic variables volatile?

Atomic variables in Java provide the same memory semantics as a volatile variable, but with an added feature of making non-atomic operation atomic. It provides a method to perform atomic increment, decrement, compare-and-swap (CAS) operations.


2 Answers

The visibility semantics are exactly the same, the situation where using the atomic primitives is useful is when you need to use their atomic methods.

For example:

if (volatileBoolean) {
    volatileBoolean = !volatileBoolean;
}

could create issues in a multi threaded environment as the variable could change between the two lines. If you need the test&assignment to be atomic, you can use:

atomicBoolean.compareAndSet(true, false);
like image 134
assylias Avatar answered Sep 20 '22 04:09

assylias


Using a plain volatile is simpler and more efficient if all you want to do is set or get the value. (But not get&set the value)

If you want more operations like getAndIncrement or compareAndSwap you need to use the AtomicXxxx classes.

like image 22
Peter Lawrey Avatar answered Sep 20 '22 04:09

Peter Lawrey