Why does the acquire() method in Semaphores not have to be synchronized?

后端 未结 3 1393
半阙折子戏
半阙折子戏 2021-01-02 23:30

I am getting into Semaphores in Java and was reading this article http://docs.oracle.com/javase/1.5.0/docs/api/java/util/concurrent/Semaphore.html . The only thing I don\'t

相关标签:
3条回答
  • 2021-01-03 00:05

    synchronization is guaranteed by AbstractQueuedSynchronizer with CAS operations

    see the javadoc here

    0 讨论(0)
  • 2021-01-03 00:20

    Semaphores ought to be fast and therefore use the atomic concurrency primitives from the Unsafe class, like CAS (compare and swap).

    With these primitives synchronization happens on a much lower level and monitors are not needed. (Lock-free synchronization).

    In fact the synchronization is performed by a loop continously using CAS until the expected value equals the written/read value.

    0 讨论(0)
  • 2021-01-03 00:22

    Or, does the semaphore itself handle the synchronization?

    Yes that's basically it. Semaphores are thread safe as explained in the javadoc:

    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.

    Most operations on the objects in the java.util.concurrent package are thread safe. More details are provided at the very bottom of the package javadoc.

    0 讨论(0)
提交回复
热议问题