Search code examples
javamultithreadingmutexsemaphorevolatile

Using volatile variables and semaphores - Java


I'm starting with Threads, Semaphores, volatile variables, etc. I wonder if when I'm using Semaphores it is necessary to define the variable as volatile, I mean:

Having 2 Threads, one increases and the other decreases the variable for example and obviously, before each access I have a mutex that controls at any time only one thread is "playing" with the variable.

It would be necessary to define as volatile?


Solution

  • From API doc of Semaphore:

    Memory consistency effects: Actions in a thread prior to calling a "release" method such as release() happen-before actions following a successful "acquire" method such as acquire() in another thread.

    So it is safe to read/write variables that are guarded by a semaphore. No need to declare them as volatile.