Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

atomic increment of long variable?

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 ??

like image 427
Mahesh Gupta Avatar asked Feb 01 '12 20:02

Mahesh Gupta


4 Answers

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

like image 105
Aravind Yarram Avatar answered Oct 16 '22 13:10

Aravind Yarram


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.

like image 20
Ted Hopp Avatar answered Oct 16 '22 14:10

Ted Hopp


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.

like image 25
user949300 Avatar answered Oct 16 '22 14:10

user949300


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.

like image 39
Bartvbl Avatar answered Oct 16 '22 12:10

Bartvbl