DebugMutex.java revision 608:7e06bf1dcb09
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
39package 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 * <p>This version adds some debugging capability: it will detect an attempt by a thread
131 * that holds the lock to acquire it for a second time, and also an attempt by a thread that
132 * does not hold the mutex to release it.
133 * @see Semaphore
134 * <p>[<a href="http://gee.cs.oswego.edu/dl/classes/EDU/oswego/cs/dl/util/concurrent/intro.html"> Introduction to this package. </a>]
135**/
136
137import org.omg.CORBA.INTERNAL ;
138
139public class DebugMutex implements Sync  {
140
141  /** The lock status **/
142  protected boolean inuse_ = false;
143  protected Thread holder_ = null;
144
145  public void acquire() throws InterruptedException {
146    if (Thread.interrupted()) throw new InterruptedException();
147    synchronized(this) {
148      Thread thr = Thread.currentThread();
149      if (holder_ == thr)
150        throw new INTERNAL(
151            "Attempt to acquire Mutex by thread holding the Mutex" ) ;
152
153      try {
154        while (inuse_) wait();
155        inuse_ = true;
156        holder_ = Thread.currentThread();
157      }
158      catch (InterruptedException ex) {
159        notify();
160        throw ex;
161      }
162    }
163  }
164
165  public synchronized void release()  {
166    Thread thr = Thread.currentThread();
167    if (thr != holder_)
168        throw new INTERNAL(
169            "Attempt to release Mutex by thread not holding the Mutex" ) ;
170    holder_ = null;
171    inuse_ = false;
172    notify();
173  }
174
175
176  public boolean attempt(long msecs) throws InterruptedException {
177    if (Thread.interrupted()) throw new InterruptedException();
178    synchronized(this) {
179      Thread thr = Thread.currentThread() ;
180
181      if (!inuse_) {
182        inuse_ = true;
183        holder_ = thr;
184        return true;
185      } else if (msecs <= 0)
186        return false;
187      else {
188        long waitTime = msecs;
189        long start = System.currentTimeMillis();
190        try {
191          for (;;) {
192            wait(waitTime);
193            if (!inuse_) {
194              inuse_ = true;
195              holder_ = thr;
196              return true;
197            }
198            else {
199              waitTime = msecs - (System.currentTimeMillis() - start);
200              if (waitTime <= 0)
201                return false;
202            }
203          }
204        }
205        catch (InterruptedException ex) {
206          notify();
207          throw ex;
208        }
209      }
210    }
211  }
212}
213