Class AdjustableSemaphore


  • @ThreadSafe
    public final class AdjustableSemaphore
    extends java.lang.Object
    A simple implementation of an adjustable semaphore.
    • Constructor Summary

      Constructors 
      Constructor Description
      AdjustableSemaphore​(int maxPermits)
      New instances should be configured with setMaxPermits().
    • Method Summary

      All Methods Instance Methods Concrete Methods 
      Modifier and Type Method Description
      void acquire()
      Get a permit, blocking if necessary.
      int availablePermits()  
      void release()
      Release a permit back to the semaphore.
      void setMaxPermits​(int newMax)
      Set the max number of permits.
      boolean tryAcquire​(long timeout, java.util.concurrent.TimeUnit unit)  
      • Methods inherited from class java.lang.Object

        clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
    • Constructor Detail

      • AdjustableSemaphore

        public AdjustableSemaphore​(int maxPermits)
        New instances should be configured with setMaxPermits().
    • Method Detail

      • setMaxPermits

        public void setMaxPermits​(int newMax)

        Set the max number of permits. Must be greater than zero.

        Note that if there are more than the new max number of permits currently outstanding, any currently blocking threads or any new threads that start to block after the call will wait until enough permits have been released to have the number of outstanding permits fall below the new maximum. In other words, it does what you probably think it should.

      • release

        public void release()
        Release a permit back to the semaphore. Make sure not to double-release.
      • acquire

        public void acquire()
                     throws java.lang.InterruptedException
        Get a permit, blocking if necessary.
        Throws:
        java.lang.InterruptedException - if interrupted while waiting for a permit
      • tryAcquire

        public boolean tryAcquire​(long timeout,
                                  java.util.concurrent.TimeUnit unit)
                           throws java.lang.InterruptedException
        Throws:
        java.lang.InterruptedException
      • availablePermits

        public int availablePermits()