1 /*
   2  * Copyright (c) 2001, 2002, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 
  26 /*
  27   File: Mutex.java
  28 
  29   Originally written by Doug Lea and released into the public domain.
  30   This may be used for any purposes whatsoever without acknowledgment.
  31   Thanks for the assistance and support of Sun Microsystems Labs,
  32   and everyone contributing, testing, and using this code.
  33 
  34   History:
  35   Date       Who                What
  36   11Jun1998  dl               Create public version
  37 */
  38 
  39 package com.sun.corba.se.impl.orbutil.concurrent;
  40 
  41 /**
  42  * A simple non-reentrant mutual exclusion lock.
  43  * The lock is free upon construction. Each acquire gets the
  44  * lock, and each release frees it. Releasing a lock that
  45  * is already free has no effect.
  46  * <p>
  47  * This implementation makes no attempt to provide any fairness
  48  * or ordering guarantees. If you need them, consider using one of
  49  * the Semaphore implementations as a locking mechanism.
  50  * <p>
  51  * <b>Sample usage</b><br>
  52  * <p>
  53  * Mutex can be useful in constructions that cannot be
  54  * expressed using java synchronized blocks because the
  55  * acquire/release pairs do not occur in the same method or
  56  * code block. For example, you can use them for hand-over-hand
  57  * locking across the nodes of a linked list. This allows
  58  * extremely fine-grained locking,  and so increases
  59  * potential concurrency, at the cost of additional complexity and
  60  * overhead that would normally make this worthwhile only in cases of
  61  * extreme contention.
  62  * <pre>
  63  * class Node {
  64  *   Object item;
  65  *   Node next;
  66  *   Mutex lock = new Mutex(); // each node keeps its own lock
  67  *
  68  *   Node(Object x, Node n) { item = x; next = n; }
  69  * }
  70  *
  71  * class List {
  72  *    protected Node head; // pointer to first node of list
  73  *
  74  *    // Use plain java synchronization to protect head field.
  75  *    //  (We could instead use a Mutex here too but there is no
  76  *    //  reason to do so.)
  77  *    protected synchronized Node getHead() { return head; }
  78  *
  79  *    boolean search(Object x) throws InterruptedException {
  80  *      Node p = getHead();
  81  *      if (p == null) return false;
  82  *
  83  *      //  (This could be made more compact, but for clarity of illustration,
  84  *      //  all of the cases that can arise are handled separately.)
  85  *
  86  *      p.lock.acquire();              // Prime loop by acquiring first lock.
  87  *                                     //    (If the acquire fails due to
  88  *                                     //    interrupt, the method will throw
  89  *                                     //    InterruptedException now,
  90  *                                     //    so there is no need for any
  91  *                                     //    further cleanup.)
  92  *      for (;;) {
  93  *        if (x.equals(p.item)) {
  94  *          p.lock.release();          // release current before return
  95  *          return true;
  96  *        }
  97  *        else {
  98  *          Node nextp = p.next;
  99  *          if (nextp == null) {
 100  *            p.lock.release();       // release final lock that was held
 101  *            return false;
 102  *          }
 103  *          else {
 104  *            try {
 105  *              nextp.lock.acquire(); // get next lock before releasing current
 106  *            }
 107  *            catch (InterruptedException ex) {
 108  *              p.lock.release();    // also release current if acquire fails
 109  *              throw ex;
 110  *            }
 111  *            p.lock.release();      // release old lock now that new one held
 112  *            p = nextp;
 113  *          }
 114  *        }
 115  *      }
 116  *    }
 117  *
 118  *    synchronized void add(Object x) { // simple prepend
 119  *      // The use of `synchronized'  here protects only head field.
 120  *      // The method does not need to wait out other traversers
 121  *      // who have already made it past head.
 122  *
 123  *      head = new Node(x, head);
 124  *    }
 125  *
 126  *    // ...  other similar traversal and update methods ...
 127  * }
 128  * </pre>
 129  * <p>
 130  * @see Semaphore
 131  * <p>[<a href="http://gee.cs.oswego.edu/dl/classes/EDU/oswego/cs/dl/util/concurrent/intro.html"> Introduction to this package. </a>]
 132 **/
 133 
 134 public class Mutex implements Sync  {
 135 
 136   /** The lock status **/
 137   protected boolean inuse_ = false;
 138 
 139   public void acquire() throws InterruptedException {
 140     if (Thread.interrupted()) throw new InterruptedException();
 141     synchronized(this) {
 142       try {
 143         while (inuse_) wait();
 144         inuse_ = true;
 145       }
 146       catch (InterruptedException ex) {
 147         notify();
 148         throw ex;
 149       }
 150     }
 151   }
 152 
 153   public synchronized void release()  {
 154     inuse_ = false;
 155     notify();
 156   }
 157 
 158 
 159   public boolean attempt(long msecs) throws InterruptedException {
 160     if (Thread.interrupted()) throw new InterruptedException();
 161     synchronized(this) {
 162       if (!inuse_) {
 163         inuse_ = true;
 164         return true;
 165       }
 166       else if (msecs <= 0)
 167         return false;
 168       else {
 169         long waitTime = msecs;
 170         long start = System.currentTimeMillis();
 171         try {
 172           for (;;) {
 173             wait(waitTime);
 174             if (!inuse_) {
 175               inuse_ = true;
 176               return true;
 177             }
 178             else {
 179               waitTime = msecs - (System.currentTimeMillis() - start);
 180               if (waitTime <= 0)
 181                 return false;
 182             }
 183           }
 184         }
 185         catch (InterruptedException ex) {
 186           notify();
 187           throw ex;
 188         }
 189       }
 190     }
 191   }
 192 
 193 }