Search code examples
javamultithreadingconcurrencyjava.util.concurrentjava-memory-model

Should I synchronize to avoid visiblity issues when using java.util.concurrent classes?


When using any of the java.util.concurrent classes, do I still need to synchronize access on the instance to avoid visibility issues between difference threads?

Elaborating the question a bit more

When using an instance of java.util.concurrent, is it possible that one thread modify the instance (i.e., put an element in a concurrent hashmap) and a subsequent thread won't be seeing the modification?

My question arises from the fact that The Java Memory Model allows threads to cache values instead of fetching them directly from memory if the access to the value is not synchronized.


Solution

  • On the java.util.concurrent package Memory Consistency Properties, you can check the Javadoc API for the package:

    The methods of all classes in java.util.concurrent and its subpackages extend these guarantees to higher-level synchronization. In particular:

    • Actions in a thread prior to placing an object into any concurrent collection happen-before actions subsequent to the access or removal of that element from the collection in another thread.
      [...]
    • Actions prior to "releasing" synchronizer methods such as
      Lock.unlock, Semaphore.release, and
      CountDownLatch.countDown
      happen-before actions subsequent to a successful "acquiring" method such as Lock.lock, Semaphore.acquire, Condition.await, and CountDownLatch.await on the same synchronizer object in another thread.
      [...]

    So, the classes in this package make sure of the concurrency, making use of a set of classes for thread control (Lock, Semaphore, etc.). This classes handle the happen-before logic programmatically, i.e. managing a FIFO stack of concurrent threads, locking and releasing current and subsequent threads (i.e. using Thread.wait() and Thread.resume(), etc.

    Then, (theoretically) you don't need to synchronize your statements accessing this classes, because they are controlling concurrent threads access programmatically.