1 package org.columba.core.base; 17 18 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 } 51 } 52 } 53 54 public boolean tryToGetLock(Object theLocker) { 55 mutex.lock(); 56 if ((this.locker == theLocker) && (theLocker != null)) { 58 mutex.release(); 59 return true; 60 } 61 62 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 } 84 | Popular Tags |