01: /*--------------------------------------------------------------------------*
02: | Copyright (C) 2006 Christopher Kohlhaas |
03: | |
04: | This program is free software; you can redistribute it and/or modify |
05: | it under the terms of the GNU General Public License as published by the |
06: | Free Software Foundation. A copy of the license has been included with |
07: | these distribution in the COPYING file, if not go to www.fsf.org |
08: | |
09: | As a special exception, you are granted the permissions to link this |
10: | program with every library, which license fulfills the Open Source |
11: | Definition as published by the Open Source Initiative (OSI). |
12: *--------------------------------------------------------------------------*/
13: package org.rapla.components.util;
14:
15: /** Mutex-lock for synchronization in multithreaded enviroments.*/
16: public class Mutex {
17: boolean locked = false;
18: boolean debugging = false;
19: String name;
20:
21: public Mutex() {
22: this .name = "";
23: }
24:
25: public Mutex(String name) {
26: this .name = name;
27: }
28:
29: /** tries to aquire a lock. If the lock is hold by another thread, the current thread will
30: * wait until the lock is released.
31: * */
32: final public synchronized void aquire() throws InterruptedException {
33: aquire(0);
34: }
35:
36: /** Releases a lock. All threads that are waiting for the lock gets notified, but only one can
37: * continue executing the aquire method (because its synchronized) and get the new lock.*/
38: final public synchronized void release() {
39: log("Lock released");
40:
41: locked = false;
42: notifyAll();
43: }
44:
45: /** Tries to aquire a lock for the specified time and returns false, if the lock can't be aquired in that time.*/
46: final public synchronized boolean aquire(int time)
47: throws InterruptedException {
48: log("Try to aquire lock");
49:
50: if (time <= 0) {
51: while (locked) {
52: wait();
53: }
54: } else {
55: long startTime = System.currentTimeMillis();
56: long currentTime = startTime;
57:
58: //The synchronization monitor will be released during wait
59: while (locked) {
60: long diff = (currentTime - startTime);
61: if (diff >= time) {
62: log("Timeout when waiting for the log");
63: return false;
64: }
65: //Many Threads can be in the aquire method (but they will loose the monitor at this point)
66: wait(time - diff);
67: currentTime = System.currentTimeMillis();
68: }
69: }
70: // Only one thread can get the monitor in the aquire method,
71: //and continue after wait. So the next state changing call is thread safe.
72: locked = true;
73: log("Lock aquired");
74: return true;
75: }
76:
77: protected String getLoggingPrefix() {
78: return "Mutex " + name + " "
79: + Thread.currentThread().toString() + " ";
80: }
81:
82: protected void log(String message) {
83: if (debugging)
84: System.out.println(getLoggingPrefix() + message);
85: }
86: }
|