Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 798
WikiOverflow Avatar asked Sep 27 '26 19:09

WikiOverflow


1 Answers

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.

like image 153
isnot2bad Avatar answered Sep 29 '26 09:09

isnot2bad



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!