Class ReentrantSemaphore


  • public class ReentrantSemaphore
    extends Object
    Management of a Reentrant Semaphore.

    When a thread is calling several times the acquire() method, only the first call is acquiring effectively a permits.
    The advantage of this behavior is not getting a self thread blocking in case of several semaphore permission requests.

    Author:
    silveryocha
    See Also:
    Semaphore
    • Constructor Detail

      • ReentrantSemaphore

        public ReentrantSemaphore​(int permits)
        Creates a reentrant Semaphore with the given number of permits.

        The semaphore will guarantee first-in first-out granting of permits under contention.

        Parameters:
        permits - the initial number of permits available. This value may be zero or negative, in which case the semaphore is ignored and no thread blocking is performed.
    • Method Detail

      • acquire

        public void acquire()
                     throws InterruptedException
        Acquires a permit from this semaphore, blocking until one is available, or the thread is interrupted.

        If a thread has already acquired successfully then it does not acquire again and it is not blocked

        Acquires a permit, if one is available and returns immediately, reducing the number of available permits by one.

        If no permit is available then the current thread becomes disabled for thread scheduling purposes and lies dormant until one of two things happens:

        • Some other thread invokes the release() method for this semaphore and the current thread is next to be assigned a permit; or
        • Some other thread interrupts the current thread.

        If the current thread:

        • has its interrupted status set on entry to this method; or
        • is interrupted while waiting for a permit,
        then InterruptedException is thrown and the current thread's interrupted status is cleared.
        Throws:
        InterruptedException - if the current thread is interrupted
      • release

        public void release()
        Releases a permit, returning it to the semaphore.

        Releases a permit, increasing the number of available permits by one. If any threads are trying to acquire a permit, then one is selected and given the permit that was just released. That thread is (re)enabled for thread scheduling purposes.

        There is no requirement that a thread that releases a permit must have acquired that permit by calling acquire(). Correct usage of a semaphore is established by programming convention in the application.