01: //The contents of this file are subject to the Mozilla Public License Version 1.1
02: //(the "License"); you may not use this file except in compliance with the
03: //License. You may obtain a copy of the License at http://www.mozilla.org/MPL/
04: //
05: //Software distributed under the License is distributed on an "AS IS" basis,
06: //WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
07: //for the specific language governing rights and
08: //limitations under the License.
09: //
10: //The Original Code is "The Columba Project"
11: //
12: //The Initial Developers of the Original Code are Frederik Dietz and Timo Stich.
13: //Portions created by Frederik Dietz and Timo Stich are Copyright (C) 2003.
14: //
15: //All Rights Reserved.
16: package org.columba.core.base;
17:
18: /**
19: * @author timo
20: *
21: * To change this generated comment edit the template variable "typecomment":
22: * Window>Preferences>Java>Templates. To enable and disable the creation of type
23: * comments go to Window>Preferences>Java>Code Generation.
24: */
25: public class Lock {
26: private boolean locked;
27:
28: private Object locker;
29:
30: private Mutex mutex;
31:
32: public Lock() {
33: locked = false;
34: mutex = new Mutex();
35: }
36:
37: public synchronized void getLock(Object theLocker) {
38: mutex.lock();
39: if (this .locker == theLocker) {
40: mutex.release();
41: return;
42: }
43: mutex.release();
44:
45: while (!tryToGetLock(theLocker)) {
46: try {
47: wait();
48: } catch (InterruptedException e) {
49: // nothing to do
50: }
51: }
52: }
53:
54: public boolean tryToGetLock(Object theLocker) {
55: mutex.lock();
56: // Is it already locked from locker ?
57: if ((this .locker == theLocker) && (theLocker != null)) {
58: mutex.release();
59: return true;
60: }
61:
62: // Check if locked
63: if (locked) {
64: mutex.release();
65: return false;
66: }
67: locked = true;
68: this .locker = theLocker;
69: mutex.release();
70:
71: return true;
72: }
73:
74: public synchronized void release(Object theLocker) {
75: mutex.lock();
76: if ((this .locker == theLocker) || (this .locker == null)) {
77: locked = false;
78: }
79: notify();
80:
81: mutex.release();
82: }
83: }
|