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?
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.
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.
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.
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);
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With