Semaphore.java

  1. /*
  2.   File: Semaphore.java

  3.   Originally written by Doug Lea and released into the public domain.
  4.   This may be used for any purposes whatsoever without acknowledgment.
  5.   Thanks for the assistance and support of Sun Microsystems Labs,
  6.   and everyone contributing, testing, and using this code.

  7.   History:
  8.   Date       Who                What
  9.   11Jun1998  dl               Create public version
  10.    5Aug1998  dl               replaced int counters with longs
  11.   24Aug1999  dl               release(n): screen arguments
  12. */

  13. package org.dbunit.util.concurrent;

  14. import org.slf4j.Logger;
  15. import org.slf4j.LoggerFactory;

  16. /**
  17.  * Base class for counting semaphores.
  18.  * Conceptually, a semaphore maintains a set of permits.
  19.  * Each acquire() blocks if necessary
  20.  * until a permit is available, and then takes it.
  21.  * Each release adds a permit. However, no actual permit objects
  22.  * are used; the Semaphore just keeps a count of the number
  23.  * available and acts accordingly.
  24.  * <p>
  25.  * A semaphore initialized to 1 can serve as a mutual exclusion
  26.  * lock.
  27.  * <p>
  28.  * Different implementation subclasses may provide different
  29.  * ordering guarantees (or lack thereof) surrounding which
  30.  * threads will be resumed upon a signal.
  31.  * <p>
  32.  * The default implementation makes NO
  33.  * guarantees about the order in which threads will
  34.  * acquire permits. It is often faster than other implementations.
  35.  * <p>
  36.  * <b>Sample usage.</b> Here is a class that uses a semaphore to
  37.  * help manage access to a pool of items.
  38.  * <pre>
  39.  * class Pool {
  40.  *   static final MAX_AVAILABLE = 100;
  41.  *   private final Semaphore available = new Semaphore(MAX_AVAILABLE);
  42.  *  
  43.  *   public Object getItem() throws InterruptedException { // no synch
  44.  *     available.acquire();
  45.  *     return getNextAvailableItem();
  46.  *   }
  47.  *
  48.  *   public void putItem(Object x) { // no synch
  49.  *     if (markAsUnused(x))
  50.  *       available.release();
  51.  *   }
  52.  *
  53.  *   // Not a particularly efficient data structure; just for demo
  54.  *
  55.  *   protected Object[] items = ... whatever kinds of items being managed
  56.  *   protected boolean[] used = new boolean[MAX_AVAILABLE];
  57.  *
  58.  *   protected synchronized Object getNextAvailableItem() {
  59.  *     for (int i = 0; i < MAX_AVAILABLE; ++i) {
  60.  *       if (!used[i]) {
  61.  *          used[i] = true;
  62.  *          return items[i];
  63.  *       }
  64.  *     }
  65.  *     return null; // not reached
  66.  *   }
  67.  *
  68.  *   protected synchronized boolean markAsUnused(Object item) {
  69.  *     for (int i = 0; i < MAX_AVAILABLE; ++i) {
  70.  *       if (item == items[i]) {
  71.  *          if (used[i]) {
  72.  *            used[i] = false;
  73.  *            return true;
  74.  *          }
  75.  *          else
  76.  *            return false;
  77.  *       }
  78.  *     }
  79.  *     return false;
  80.  *   }
  81.  *
  82.  * }
  83.  *</pre>
  84.  * <p>[<a href="http://gee.cs.oswego.edu/dl/classes/EDU/oswego/cs/dl/util/concurrent/intro.html"> Introduction to this package. </a>]
  85.  *
  86.  * @author Doug Lea
  87.  * @author Last changed by: $Author$
  88.  * @version $Revision$ $Date$
  89.  * @since ? (pre 2.1)
  90.  */
  91. public class Semaphore implements Sync  {

  92.     /**
  93.      * Logger for this class
  94.      */
  95.     private static final Logger logger = LoggerFactory.getLogger(Semaphore.class);

  96.   /** current number of available permits **/
  97.   protected long permits_;

  98.   /**
  99.    * Create a Semaphore with the given initial number of permits.
  100.    * Using a seed of one makes the semaphore act as a mutual exclusion lock.
  101.    * Negative seeds are also allowed, in which case no acquires will proceed
  102.    * until the number of releases has pushed the number of permits past 0.
  103.   **/
  104.   public Semaphore(long initialPermits) {  permits_ = initialPermits; }


  105.   /** Wait until a permit is available, and take one **/
  106.   public void acquire() throws InterruptedException {
  107.         logger.debug("acquire() - start");

  108.     if (Thread.interrupted()) throw new InterruptedException();
  109.     synchronized(this) {
  110.       try {
  111.         while (permits_ <= 0) wait();
  112.         --permits_;
  113.       }
  114.       catch (InterruptedException ex) {
  115.         notify();
  116.         throw ex;
  117.       }
  118.     }
  119.   }

  120.   /** Wait at most msecs millisconds for a permit. **/
  121.   public boolean attempt(long msecs) throws InterruptedException {
  122.         logger.debug("attempt(msecs={}) - start", String.valueOf(msecs));

  123.     if (Thread.interrupted()) throw new InterruptedException();

  124.     synchronized(this) {
  125.       if (permits_ > 0) {
  126.         --permits_;
  127.         return true;
  128.       }
  129.       else if (msecs <= 0)  
  130.         return false;
  131.       else {
  132.         try {
  133.           long startTime = System.currentTimeMillis();
  134.           long waitTime = msecs;
  135.          
  136.           for (;;) {
  137.             wait(waitTime);
  138.             if (permits_ > 0) {
  139.               --permits_;
  140.               return true;
  141.             }
  142.             else {
  143.               waitTime = msecs - (System.currentTimeMillis() - startTime);
  144.               if (waitTime <= 0)
  145.                 return false;
  146.             }
  147.           }
  148.         }
  149.         catch(InterruptedException ex) {
  150.           notify();
  151.           throw ex;
  152.         }
  153.       }
  154.     }
  155.   }

  156.   /** Release a permit **/
  157.   public synchronized void release() {
  158.         logger.debug("release() - start");

  159.     ++permits_;
  160.     notify();
  161.   }


  162.   /**
  163.    * Release N permits. <code>release(n)</code> is
  164.    * equivalent in effect to:
  165.    * <pre>
  166.    *   for (int i = 0; i < n; ++i) release();
  167.    * </pre>
  168.    * <p>
  169.    * But may be more efficient in some semaphore implementations.
  170.    * @exception IllegalArgumentException if n is negative.
  171.    **/
  172.   public synchronized void release(long n) {
  173.         logger.debug("release(n={}) - start", String.valueOf(n));

  174.     if (n < 0) throw new IllegalArgumentException("Negative argument");

  175.     permits_ += n;
  176.     for (long i = 0; i < n; ++i) notify();
  177.   }

  178.   /**
  179.    * Return the current number of available permits.
  180.    * Returns an accurate, but possibly unstable value,
  181.    * that may change immediately after returning.
  182.    **/
  183.   public synchronized long permits() {
  184.     return permits_;
  185.   }

  186. }