Could somebody please clarify my doubt on AtomicReferences. As par java memory model reading & writing references is always an atomic operation irrespective of 32 bit or 64 bit machine. So in what scenario using AtomicRefernce will be useful.
Asked
Active
Viewed 79 times
1
-
Have you looked at the Javadoc of AtomicReference? You'll find a number of methods that allow you to do other things than just changing the value of a reference. It's useful for those methods. – Erwin Bolwidt May 06 '15 at 05:11
-
@TheLostMind The question is not a duplicated of that other one. The titles suggest that but what's being asked is different. The other question doesn't mention the java memory model. – Daniel Sperry May 06 '15 at 05:19
-
1@DanielSperry - [this](http://stackoverflow.com/questions/281132/java-volatile-reference-vs-atomicreference?rq=1) will also help the OP. The related question (and the ones related to it) will help the OP. If the OP has a more *specific* question, I will re-open it – TheLostMind May 06 '15 at 05:21
-
The JMM ensures that there is no read or write tearing, which would cause data corruption due to multiple memory operations. This is typically caused by misaligned memory locations. A volatile / atomic reference emits memory barriers to ensure visibility across threads. These are both atomic in the definition of being single irreducible unit from the programmer's perspective, but in reference to two very different operations. – Ben Manes May 06 '15 at 08:38
1 Answers
0
There are other operations provided by AtomicReference that you can't implement with normal references.
For instance to make sure which value your are replacing:
ref.compareAndSet(expectedCurrentValue, newValue);
To get the last value and replace with something else:
oldValue = ref.getAndSet(newValue);
With AtomicReference you can do those operations safely even when multiple threads are trying to access the same references.

Daniel Sperry
- 4,381
- 4
- 31
- 41