if a long variable is declared as :-
private volatile long counter = 0;
now if i increment it using pre-increment operator, then would the operation be atomic ?
if yes, then will it be more efficient than java.util.concurrent.atomic.AtomicLong
object's increment ??
volatile
keyword only solves visibility problem. You have to use AtomicLong
or synchronized
method/block for atomicity (Atomicity in concurrent programming).
One more article that came out today: Demonstrating when volatile is required
The pre-increment operator is not atomic. Also, incrementing a volatile long
is likely to be less efficient than using AtomicLong
on almost all platforms, because the latter is supported by hardware.
The short answer is No. You will need to synchronize the method that increments counter, or, preferably, use an AtomicLong.
For the record, ++ operators are not atomic even on integers.
A volatile variable is not the same as an atomic variable.
For volatile variables, the java compiler will attempt to minimize shuffling commands around for the sake of efficiency (don't ask me the details of that.. ), to avoid concurrency problems.
Atomic variables are explicitly made for atomic operations, like in your case incrementing a variable atomically.
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