semaphores and semaphore use principles

What is the semaphore (semaphore)

  • JDK is a built-synchronizer, he can be achieved through multi-threaded concurrent access to a common resource request
  • It can be seen as a counter, when the counter value is less than the license limit, the method thread can acquire a license to continue to get executed, and calls the release method, you can make the counter value is decremented by one

Commonly used methods important

1public Semaphore(int permits)
   // 创建一个给定许可数量的信号量对象,且默认以非公平锁方式获取资源

2public Semaphore(int permits, boolean fair)
   // 创建一个给定许可数量的信号量对象,且是否公平方式由传入的fair布尔参数值决定

3public void acquire() 
   // 从此信号量获取一个许可,当许可数量小于零时,则阻塞等待
   
4public void acquire(int permits)  
   // 从此信号量获取permits个许可,当许可数量小于零时,则阻塞等待,但是当阻塞等待的线程被唤醒后发现被中断过的话则会抛InterruptedException异常
   
5public void acquireUninterruptibly(int permits)   
   // 从此信号量获取permits个许可,当许可数量小于零时,则阻塞等待,但是当阻塞等待的线程被唤醒后发现被中断过的话不会抛InterruptedException异常
   
6public void release()
   // 释放一个许可

7public void acquire(int permits)
   // 释放permits个许可

The principle

Here Insert Picture Description

  • Implement semaphore class is based on the AQS synchronizers to achieve, whether it is fair or unfair is based on a shared mode AQS, but there are differences in the operating logic.
    Here Insert Picture Description
    Here Insert Picture Description
  • Syn internal subclass the parent class is abstract pattern FairSync fair and non-equity modes NonfairSync class
  • Which provides two constructors, two parameters for the maximum number of licenses and whether to use Fair mode.

Non-equity modes to achieve

Here Insert Picture Description
Here Insert Picture Description

  • It provides a method of non-equity modes semaphore acquired nonfairTryAcquireShared
    • In the case of the number of licenses allowed (remaining <0), can make all the threads of the spin operator (CAS)
    • When the remaining amount is less than 0 signal is a negative return (return remaining), causes the thread enters the wait queue (the AQS)
  • tryReleaseShared method provides release semaphore operation
    • CAS signal by the spin operation amount added to the current number of remaining licenses

Equitable mode

Here Insert Picture Description

  • Fair and unfair mode mode main difference is the mechanism in acquiring semaphore
  • Different places in two lines of code on the box, it checks if there is already a waiting queue, if there is direct (return -1) AQS synchronization will allow the current thread into the wait queue

example

Here Insert Picture Description
Here Insert Picture Description

Published 20 original articles · won praise 0 · Views 255

Guess you like

Origin blog.csdn.net/white_zzZ/article/details/103954859