javamultithreadingsynchronizationvolatileatomicreference

Correct understanding of concepts like volatile, syncronized and AtomicReference?


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:

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

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

  3. 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


Solution

  • a) What is the difference bwteen declaring a (shared between threads) variable volatile and not to?

    If it isn't volatile, a write to it by one thread may never be seen by any other threads.

    b) Should we always declare it volatile in we're accessing it from different threads?

    Unless it is always accessed from a synchronized block.

    c) Does it make sense to synchronize a volatile variable?

    It does, but only if the volatile variable is also accessed outside of any synchronized block.

    a) Does it make sense to declare an AtomicReference volatile?

    It definitely does, if you plan to change the instance at runtime. Usually, however, it is better to have a final AtomicReference.

    b) But synchronize it?, since AtomicReference.get is not synchronized nor the set?

    Synchronizing AtomicReference access defeats its very purpose of lock-free multithreading. Choose either synchronization or AtomicReference.