SynchronousChannel.java

  1. /*
  2.   File: SynchronousChannel.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.   17Jul1998  dl               Disabled direct semaphore permit check
  11.   31Jul1998  dl               Replaced main algorithm with one with
  12.                               better scaling and fairness properties.
  13.   25aug1998  dl               added peek
  14.   24Nov2001  dl               Replaced main algorithm with faster one.
  15. */

  16. package org.dbunit.util.concurrent;

  17. import org.slf4j.Logger;
  18. import org.slf4j.LoggerFactory;

  19. /**
  20.  * A rendezvous channel, similar to those used in CSP and Ada. Each
  21.  * put must wait for a take, and vice versa. Synchronous channels
  22.  * are well suited for handoff designs, in which an object running in
  23.  * one thread must synch up with an object running in another thread
  24.  * in order to hand it some information, event, or task.
  25.  * <p> If you only need threads to synch up without
  26.  * exchanging information, consider using a Barrier. If you need
  27.  * bidirectional exchanges, consider using a Rendezvous.  <p>
  28.  *
  29.  * <p>Read the
  30.  * <a href="http://gee.cs.oswego.edu/dl/classes/EDU/oswego/cs/dl/util/concurrent/intro.html">introduction to this package</a>
  31.  * for more details.
  32.  *
  33.  * @author Doug Lea
  34.  * @author Last changed by: $Author$
  35.  * @version $Revision$ $Date$
  36.  * @since ? (pre 2.1)
  37.  * @see <a href="http://gee.cs.oswego.edu/dl/classes/EDU/oswego/cs/dl/util/concurrent/Rendezvous.html">Rendezvous</a>
  38.  * @see <a href="http://gee.cs.oswego.edu/dl/classes/EDU/oswego/cs/dl/util/concurrent/CyclicBarrier.html">CyclicBarrier</a>
  39.  */
  40. public class SynchronousChannel implements BoundedChannel {

  41.     /**
  42.      * Logger for this class
  43.      */
  44.     private static final Logger logger = LoggerFactory.getLogger(SynchronousChannel.class);

  45.   /*
  46.     This implementation divides actions into two cases for puts:

  47.     * An arriving putter that does not already have a waiting taker
  48.       creates a node holding item, and then waits for a taker to take it.
  49.     * An arriving putter that does already have a waiting taker fills
  50.       the slot node created by the taker, and notifies it to continue.

  51.    And symmetrically, two for takes:

  52.     * An arriving taker that does not already have a waiting putter
  53.       creates an empty slot node, and then waits for a putter to fill it.
  54.     * An arriving taker that does already have a waiting putter takes
  55.       item from the node created by the putter, and notifies it to continue.

  56.    This requires keeping two simple queues: waitingPuts and waitingTakes.
  57.    
  58.    When a put or take waiting for the actions of its counterpart
  59.    aborts due to interruption or timeout, it marks the node
  60.    it created as "CANCELLED", which causes its counterpart to retry
  61.    the entire put or take sequence.
  62.   */

  63.   /**
  64.    * Special marker used in queue nodes to indicate that
  65.    * the thread waiting for a change in the node has timed out
  66.    * or been interrupted.
  67.    **/
  68.   protected static final Object CANCELLED = new Object();
  69.  
  70.   /**
  71.    * Simple FIFO queue class to hold waiting puts/takes.
  72.    **/
  73.   protected static class Queue {

  74.         /**
  75.          * Logger for this class
  76.          */
  77.         private static final Logger logger = LoggerFactory.getLogger(Queue.class);

  78.     protected LinkedNode head;
  79.     protected LinkedNode last;

  80.     protected void enq(LinkedNode p) {
  81.             logger.debug("enq(p={}) - start", p);
  82.  
  83.       if (last == null)
  84.         last = head = p;
  85.       else
  86.         last = last.next = p;
  87.     }

  88.     protected LinkedNode deq() {
  89.             logger.debug("deq() - start");

  90.       LinkedNode p = head;
  91.       if (p != null && (head = p.next) == null)
  92.         last = null;
  93.       return p;
  94.     }
  95.   }

  96.   protected final Queue waitingPuts = new Queue();
  97.   protected final Queue waitingTakes = new Queue();

  98.   /**
  99.    * @return zero --
  100.    * Synchronous channels have no internal capacity.
  101.    **/
  102.   public int capacity() {
  103.         logger.debug("capacity() - start");
  104.  return 0; }

  105.   /**
  106.    * @return null --
  107.    * Synchronous channels do not hold contents unless actively taken
  108.    **/
  109.   public Object peek() {
  110.         logger.debug("peek() - start");
  111.   return null;  }


  112.   public void put(Object x) throws InterruptedException {
  113.         logger.debug("put(x={}) - start", x);

  114.     if (x == null) throw new IllegalArgumentException();

  115.     // This code is conceptually straightforward, but messy
  116.     // because we need to intertwine handling of put-arrives first
  117.     // vs take-arrives first cases.

  118.     // Outer loop is to handle retry due to canceled waiting taker
  119.     for (;;) {

  120.       // Get out now if we are interrupted
  121.       if (Thread.interrupted()) throw new InterruptedException();

  122.       // Exactly one of item or slot will be not-null at end of
  123.       // synchronized block, depending on whether a put or a take
  124.       // arrived first.
  125.       LinkedNode slot;
  126.       LinkedNode item = null;

  127.       synchronized(this) {
  128.         // Try to match up with a waiting taker; fill and signal it below
  129.         slot = waitingTakes.deq();

  130.         // If no takers yet, create a node and wait below
  131.         if (slot == null)
  132.           waitingPuts.enq(item = new LinkedNode(x));
  133.       }

  134.       if (slot != null) { // There is a waiting taker.
  135.         // Fill in the slot created by the taker and signal taker to
  136.         // continue.
  137.         synchronized(slot) {
  138.           if (slot.value != CANCELLED) {
  139.             slot.value = x;
  140.             slot.notify();
  141.             return;
  142.           }
  143.           // else the taker has canceled, so retry outer loop
  144.         }
  145.       }

  146.       else {
  147.         // Wait for a taker to arrive and take the item.
  148.         synchronized(item) {
  149.           try {
  150.             while (item.value != null)
  151.               item.wait();
  152.             return;
  153.           }
  154.           catch (InterruptedException ie) {
  155.             // If item was taken, return normally but set interrupt status
  156.             if (item.value == null) {
  157.               Thread.currentThread().interrupt();
  158.               return;
  159.             }
  160.             else {
  161.               item.value = CANCELLED;
  162.               throw ie;
  163.             }
  164.           }
  165.         }
  166.       }
  167.     }
  168.   }

  169.   public Object take() throws InterruptedException {
  170.         logger.debug("take() - start");

  171.     // Entirely symmetric to put()

  172.     for (;;) {
  173.       if (Thread.interrupted()) throw new InterruptedException();

  174.       LinkedNode item;
  175.       LinkedNode slot = null;

  176.       synchronized(this) {
  177.         item = waitingPuts.deq();
  178.         if (item == null)
  179.           waitingTakes.enq(slot = new LinkedNode());
  180.       }

  181.       if (item != null) {
  182.         synchronized(item) {
  183.           Object x = item.value;
  184.           if (x != CANCELLED) {
  185.             item.value = null;
  186.             item.next = null;
  187.             item.notify();
  188.             return x;
  189.           }
  190.         }
  191.       }

  192.       else {
  193.         synchronized(slot) {
  194.           try {
  195.             for (;;) {
  196.               Object x = slot.value;
  197.               if (x != null) {
  198.                 slot.value = null;
  199.                 slot.next = null;
  200.                 return x;
  201.               }
  202.               else
  203.                 slot.wait();
  204.             }
  205.           }
  206.           catch(InterruptedException ie) {
  207.             Object x = slot.value;
  208.             if (x != null) {
  209.               slot.value = null;
  210.               slot.next = null;
  211.               Thread.currentThread().interrupt();
  212.               return x;
  213.             }
  214.             else {
  215.               slot.value = CANCELLED;
  216.               throw ie;
  217.             }
  218.           }
  219.         }
  220.       }
  221.     }
  222.   }

  223.   /*
  224.     Offer and poll are just like put and take, except even messier.
  225.    */


  226.   public boolean offer(Object x, long msecs) throws InterruptedException {
  227.       if(logger.isDebugEnabled())
  228.         logger.debug("offer(x={}, msecs={}) - start", x, String.valueOf(msecs));

  229.     if (x == null) throw new IllegalArgumentException();
  230.     long waitTime = msecs;
  231.     long startTime = 0; // lazily initialize below if needed
  232.    
  233.     for (;;) {
  234.       if (Thread.interrupted()) throw new InterruptedException();

  235.       LinkedNode slot;
  236.       LinkedNode item = null;

  237.       synchronized(this) {
  238.         slot = waitingTakes.deq();
  239.         if (slot == null) {
  240.           if (waitTime <= 0)
  241.             return false;
  242.           else
  243.             waitingPuts.enq(item = new LinkedNode(x));
  244.         }
  245.       }

  246.       if (slot != null) {
  247.         synchronized(slot) {
  248.           if (slot.value != CANCELLED) {
  249.             slot.value = x;
  250.             slot.notify();
  251.             return true;
  252.           }
  253.         }
  254.       }

  255.       long now = System.currentTimeMillis();
  256.       if (startTime == 0)
  257.         startTime = now;
  258.       else
  259.         waitTime = msecs - (now - startTime);

  260.       if (item != null) {
  261.         synchronized(item) {
  262.           try {
  263.             for (;;) {
  264.               if (item.value == null)
  265.                 return true;
  266.               if (waitTime <= 0) {
  267.                 item.value = CANCELLED;
  268.                 return false;
  269.               }
  270.               item.wait(waitTime);
  271.               waitTime = msecs - (System.currentTimeMillis() - startTime);
  272.             }
  273.           }
  274.           catch (InterruptedException ie) {
  275.             if (item.value == null) {
  276.               Thread.currentThread().interrupt();
  277.               return true;
  278.             }
  279.             else {
  280.               item.value = CANCELLED;
  281.               throw ie;
  282.             }
  283.           }
  284.         }
  285.       }
  286.     }
  287.   }

  288.   public Object poll(long msecs) throws InterruptedException {
  289.       if(logger.isDebugEnabled())
  290.         logger.debug("poll(msecs={}) - start", String.valueOf(msecs));

  291.     long waitTime = msecs;
  292.     long startTime = 0;

  293.     for (;;) {
  294.       if (Thread.interrupted()) throw new InterruptedException();

  295.       LinkedNode item;
  296.       LinkedNode slot = null;

  297.       synchronized(this) {
  298.         item = waitingPuts.deq();
  299.         if (item == null) {
  300.           if (waitTime <= 0)
  301.             return null;
  302.           else
  303.             waitingTakes.enq(slot = new LinkedNode());
  304.         }
  305.       }

  306.       if (item != null) {
  307.         synchronized(item) {
  308.           Object x = item.value;
  309.           if (x != CANCELLED) {
  310.             item.value = null;
  311.             item.next = null;
  312.             item.notify();
  313.             return x;
  314.           }
  315.         }
  316.       }

  317.       long now = System.currentTimeMillis();
  318.       if (startTime == 0)
  319.         startTime = now;
  320.       else
  321.         waitTime = msecs - (now - startTime);

  322.       if (slot != null) {
  323.         synchronized(slot) {
  324.           try {
  325.             for (;;) {
  326.               Object x = slot.value;
  327.               if (x != null) {
  328.                 slot.value = null;
  329.                 slot.next = null;
  330.                 return x;
  331.               }
  332.               if (waitTime <= 0) {
  333.                 slot.value = CANCELLED;
  334.                 return null;
  335.               }
  336.               slot.wait(waitTime);
  337.               waitTime = msecs - (System.currentTimeMillis() - startTime);
  338.             }
  339.           }
  340.           catch(InterruptedException ie) {
  341.             Object x = slot.value;
  342.             if (x != null) {
  343.               slot.value = null;
  344.               slot.next = null;
  345.               Thread.currentThread().interrupt();
  346.               return x;
  347.             }
  348.             else {
  349.               slot.value = CANCELLED;
  350.               throw ie;
  351.             }
  352.           }
  353.         }
  354.       }
  355.     }
  356.   }

  357. }