0

I have a multi-threaded environment, managed by a "pool". This pool guarantees that only one thread at a time can access the shared resource. Once the resource gets released by the thread which is currently using it, the resource returns back to the pool and can be used by other threads. Synchronization is done by using ReentrantLock inside the Pool. Should I consider using volatile for shared resource's class attributes?

Thanks.

Lazarus
  • 147
  • 13
  • 1
    ReentrantLock's unlock happens before acquire, so you shouldn't need further synchronization. – Andy Turner Apr 26 '20 at 13:53
  • This might be useful [When exactly do you use the volatile keyword in Java?](https://stackoverflow.com/questions/3488703/when-exactly-do-you-use-the-volatile-keyword-in-java) and in fact sort-of mentions what @AndyTurner noted above in an answer. – Hovercraft Full Of Eels Apr 26 '20 at 13:54
  • I have found a more specific duplicate question and have used it to close this one. Please note my [search strategy used](https://www.google.com/search?q=java+volatile+reentrantlock+site:stackoverflow.com) – Hovercraft Full Of Eels Apr 26 '20 at 13:56

1 Answers1

1

The Javadoc of ReentrantLock describes it as:

A reentrant mutual exclusion Lock with the same basic behavior and semantics as the implicit monitor lock accessed using synchronized methods and statements, but with extended capabilities.

So, an unlock() happens before a subsequent successful acquire(), just as the release of a monitor happens before a subsequent acquisition.

As such, provided the shared resources aren't accessible by any other means, you don't need further synchronization.

Andy Turner
  • 137,514
  • 11
  • 162
  • 243