01: /*
02: * Mutex.java
03: *
04: * Copyright (C) 2002-2004 Peter Graves
05: * $Id: Mutex.java,v 1.2 2004/09/09 11:13:19 piso Exp $
06: *
07: * This program is free software; you can redistribute it and/or
08: * modify it under the terms of the GNU General Public License
09: * as published by the Free Software Foundation; either version 2
10: * of the License, or (at your option) any later version.
11: *
12: * This program is distributed in the hope that it will be useful,
13: * but WITHOUT ANY WARRANTY; without even the implied warranty of
14: * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15: * GNU General Public License for more details.
16: *
17: * You should have received a copy of the GNU General Public License
18: * along with this program; if not, write to the Free Software
19: * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
20: */
21:
22: package org.armedbear.j;
23:
24: public final class Mutex {
25: private boolean inUse;
26:
27: public final boolean isInUse() {
28: return inUse;
29: }
30:
31: public void acquire() throws InterruptedException {
32: if (Thread.interrupted())
33: throw new InterruptedException();
34: synchronized (this ) {
35: try {
36: while (inUse)
37: wait();
38: inUse = true;
39: } catch (InterruptedException e) {
40: notify();
41: throw e;
42: }
43: }
44: }
45:
46: public synchronized void release() {
47: if (inUse) {
48: inUse = false;
49: notify();
50: } else
51: Debug.bug("Mutex.release() mutex not in use!");
52: }
53:
54: public boolean attempt() throws InterruptedException {
55: return attempt(0);
56: }
57:
58: public boolean attempt(long msecs) throws InterruptedException {
59: if (Thread.interrupted())
60: throw new InterruptedException();
61: synchronized (this ) {
62: if (!inUse) {
63: inUse = true;
64: return true;
65: } else if (msecs <= 0) {
66: return false;
67: } else {
68: long waitTime = msecs;
69: long start = System.currentTimeMillis();
70: try {
71: for (;;) {
72: wait(waitTime);
73: if (!inUse) {
74: inUse = true;
75: return true;
76: } else {
77: waitTime = msecs
78: - (System.currentTimeMillis() - start);
79: if (waitTime <= 0)
80: return false;
81: }
82: }
83: } catch (InterruptedException e) {
84: notify();
85: throw e;
86: }
87: }
88: }
89: }
90: }
|