atomic increment of long variable?

前端 未结 4 1080
南旧
南旧 2020-12-11 16:01

if a long variable is declared as :-

private volatile long counter = 0;

now if i increment it using pre-increment operator, then would the o

相关标签:
4条回答
  • 2020-12-11 16:33

    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.

    0 讨论(0)
  • 2020-12-11 16:47

    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.

    0 讨论(0)
  • 2020-12-11 16:51

    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.

    0 讨论(0)
  • 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

    0 讨论(0)
提交回复
热议问题