2

It occurs to me CAS alone could insure the atomicity of atomic integers. so why bother declare the underlying value volatile?

I know volatile prevents compiler and hardware reordering, and ensures the instruction order. But is that relevant here ?

What's the problem here? What is the problem without volatile?

GhostCat
  • 137,827
  • 25
  • 176
  • 248
zinking
  • 5,561
  • 5
  • 49
  • 81

2 Answers2

3

Assuming it's the Atomic* classes from java.util.concurrent.atomic package.

You are talking about two different concepts: the reference to the atomic object and the atomic object itself.

True, CAS on the same atomic integer object is atomic. But how can we be sure that the compareAndSet method calls in two threads are applied to the same object? Just like any java object that are shared by multiple threads, this is related to the safe-publication of the [atomic] object.

This is where volatile, final member variables or locking comes in useful. The reference to the object should be properly shared by multiple threads.

After rereading the question, I see you could be asking why the value member in AtomicInteger is declared volatile. For starters, not all methods are based on unsafe.compareAndSwapInt, there are simple set and get that directly access the value field, this is enough reason for this field to be volatile. I wonder it's also required for the unsafe operations.

Community
  • 1
  • 1
xiaofeng.li
  • 8,237
  • 2
  • 23
  • 30
  • I believe what OP asking is, by using your example, `volatile int` vs `AtomicInteger`. What you answered is `volatile AtomicInteger` vs `AtomicInteger` – Adrian Shum Aug 17 '16 at 06:40
  • safe-publication seems to be one point. but is it just a matter of delaying to see the value for some time? `volatile` ensures as soon as the value is updated it will be seen by all others, but without that it could delay some time? further if can accept that and I don't need `set` method does that mean I can get rid of volatile? – zinking Aug 17 '16 at 07:37
  • Well it is also possible for the update to never be seen by another thread. – xiaofeng.li Aug 17 '16 at 07:40
2

Quoting Oracle documentation:

Reads and writes are atomic for all variables declared volatile (including long and double variables).

...However, this does not eliminate all need to synchronize atomic actions, because memory consistency errors are still possible. Using volatile variables reduces the risk of memory consistency errors, because any write to a volatile variable establishes a happens-before relationship with subsequent reads of that same variable.

GhostCat
  • 137,827
  • 25
  • 176
  • 248