I would like to be sure I understood correctly these concepts. The explanations/confirmations will help me a lot and I'm sure many other programmers. So here are my understandings of these concepts, resulted from my investigation:
Volatile is used when you want to share a variable between multiple threads. a) What is the difference bwteen declaring a (shared between threads) variable volatile and not to ? b) Should we always declare it volatile in we're accessing it from different threads? c) Does it make sense to synchronize a volatile variable?
AtomicReference is a class that wraps our object and provides some atomic operations on it ( compareAndSet, lazySet and weakCompareAndSet ). This is all, no synchronization, no nothing. a) Does it make sense to declare an AtomicReference volatile? b) But synchronize it?, since AtomicReference.get is not synchronized nor the set?
Synchronization is a concept that means sequential access to a variable that is shared between multiple threads. It can be done by instance and by class. Synchronization can be added into methods headers or in code blocks. No mistery here I hope :)
Regards, Aurelian
If it isn't volatile, a write to it by one thread may never be seen by any other threads.
Unless it is always accessed from a synchronized block.
It does, but only if the volatile variable is also accessed outside of any synchronized block.
It definitely does, if you plan to change the instance at runtime. Usually, however, it is better to have a
final AtomicReference
.Synchronizing AtomicReference access defeats its very purpose of lock-free multithreading. Choose either synchronization or AtomicReference.