LinkedQueue.java

  1. /*
  2.   File: LinkedQueue.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.   25aug1998  dl               added peek
  11.   10dec1998  dl               added isEmpty
  12.   10oct1999  dl               lock on node object to ensure visibility
  13. */

  14. package org.dbunit.util.concurrent;

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

  17. /**
  18.  * A linked list based channel implementation.
  19.  * The algorithm avoids contention between puts
  20.  * and takes when the queue is not empty.
  21.  * Normally a put and a take can proceed simultaneously.
  22.  * (Although it does not allow multiple concurrent puts or takes.)
  23.  * This class tends to perform more efficently than
  24.  * other Channel implementations in producer/consumer
  25.  * applications.
  26.  * <p>[<a href="http://gee.cs.oswego.edu/dl/classes/EDU/oswego/cs/dl/util/concurrent/intro.html"> Introduction to this package. </a>]
  27.  *
  28.  *
  29.  * @author Doug Lea
  30.  * @author Last changed by: $Author$
  31.  * @version $Revision$ $Date$
  32.  * @since ? (pre 2.1)
  33.  */
  34. public class LinkedQueue implements Channel {

  35.     /**
  36.      * Logger for this class
  37.      */
  38.     private static final Logger logger = LoggerFactory.getLogger(LinkedQueue.class);


  39.   /**
  40.    * Dummy header node of list. The first actual node, if it exists, is always
  41.    * at head_.next. After each take, the old first node becomes the head.
  42.    **/
  43.   protected LinkedNode head_;        

  44.   /**
  45.    * Helper monitor for managing access to last node.
  46.    **/
  47.   protected final Object putLock_ = new Object();

  48.   /**
  49.    * The last node of list. Put() appends to list, so modifies last_
  50.    **/
  51.   protected LinkedNode last_;        

  52.   /**
  53.    * The number of threads waiting for a take.
  54.    * Notifications are provided in put only if greater than zero.
  55.    * The bookkeeping is worth it here since in reasonably balanced
  56.    * usages, the notifications will hardly ever be necessary, so
  57.    * the call overhead to notify can be eliminated.
  58.    **/
  59.   protected int waitingForTake_ = 0;  

  60.   public LinkedQueue() {
  61.     head_ = new LinkedNode(null);
  62.     last_ = head_;
  63.   }

  64.   /** Main mechanics for put/offer **/
  65.   protected void insert(Object x) {
  66.         logger.debug("insert(x=" + x + ") - start");
  67.  
  68.     synchronized(putLock_) {
  69.       LinkedNode p = new LinkedNode(x);
  70.       synchronized(last_) {
  71.         last_.next = p;
  72.         last_ = p;
  73.       }
  74.       if (waitingForTake_ > 0)
  75.         putLock_.notify();
  76.     }
  77.   }

  78.   /** Main mechanics for take/poll **/
  79.   protected synchronized Object extract() {
  80.         logger.debug("extract() - start");

  81.     synchronized(head_) {
  82.       Object x = null;
  83.       LinkedNode first = head_.next;
  84.       if (first != null) {
  85.         x = first.value;
  86.         first.value = null;
  87.         head_ = first;
  88.       }
  89.       return x;
  90.     }
  91.   }


  92.   public void put(Object x) throws InterruptedException {
  93.         logger.debug("put(x=" + x + ") - start");

  94.     if (x == null) throw new IllegalArgumentException();
  95.     if (Thread.interrupted()) throw new InterruptedException();
  96.     insert(x);
  97.   }

  98.   public boolean offer(Object x, long msecs) throws InterruptedException {
  99.         logger.debug("offer(x=" + x + ", msecs=" + msecs + ") - start");
  100.  
  101.     if (x == null) throw new IllegalArgumentException();
  102.     if (Thread.interrupted()) throw new InterruptedException();
  103.     insert(x);
  104.     return true;
  105.   }

  106.   public Object take() throws InterruptedException {
  107.         logger.debug("take() - start");

  108.     if (Thread.interrupted()) throw new InterruptedException();
  109.     // try to extract. If fail, then enter wait-based retry loop
  110.     Object x = extract();
  111.     if (x != null)
  112.       return x;
  113.     else {
  114.       synchronized(putLock_) {
  115.         try {
  116.           ++waitingForTake_;
  117.           for (;;) {
  118.             x = extract();
  119.             if (x != null) {
  120.               --waitingForTake_;
  121.               return x;
  122.             }
  123.             else {
  124.               putLock_.wait();
  125.             }
  126.           }
  127.         }
  128.         catch(InterruptedException ex) {
  129.           --waitingForTake_;
  130.           putLock_.notify();
  131.           throw ex;
  132.         }
  133.       }
  134.     }
  135.   }

  136.   public Object peek() {
  137.         logger.debug("peek() - start");

  138.     synchronized(head_) {
  139.       LinkedNode first = head_.next;
  140.       if (first != null)
  141.         return first.value;
  142.       else
  143.         return null;
  144.     }
  145.   }    


  146.   public boolean isEmpty() {
  147.         logger.debug("isEmpty() - start");

  148.     synchronized(head_) {
  149.       return head_.next == null;
  150.     }
  151.   }    

  152.   public Object poll(long msecs) throws InterruptedException {
  153.         logger.debug("poll(msecs=" + msecs + ") - start");

  154.     if (Thread.interrupted()) throw new InterruptedException();
  155.     Object x = extract();
  156.     if (x != null)
  157.       return x;
  158.     else {
  159.       synchronized(putLock_) {
  160.         try {
  161.           long waitTime = msecs;
  162.           long start = (msecs <= 0)? 0 : System.currentTimeMillis();
  163.           ++waitingForTake_;
  164.           for (;;) {
  165.             x = extract();
  166.             if (x != null || waitTime <= 0) {
  167.               --waitingForTake_;
  168.               return x;
  169.             }
  170.             else {
  171.               putLock_.wait(waitTime);
  172.               waitTime = msecs - (System.currentTimeMillis() - start);
  173.             }
  174.           }
  175.         }
  176.         catch(InterruptedException ex) {
  177.           --waitingForTake_;
  178.           putLock_.notify();
  179.           throw ex;
  180.         }
  181.       }
  182.     }
  183.   }
  184. }