1 9 package javolution.util; 10 11 20 public class ReentrantLock { 21 22 25 private Thread _owner; 26 27 30 private long _count; 31 32 35 public ReentrantLock() { 36 } 37 38 41 public void lock() { 42 Thread caller = Thread.currentThread(); 43 synchronized (this) { 44 if (caller == _owner) { 45 _count++; 46 } else { 47 try { 48 while (_owner != null) { 49 this.wait(); 50 } 51 _owner = caller; 52 _count = 1; 53 } catch (InterruptedException exception) { 54 return; 55 } 56 } 57 } 58 } 59 60 67 public boolean tryLock() { 68 synchronized (this) { 69 if (_owner == null) { 70 lock(); 71 return true; 72 } else { 73 return false; 74 } 75 } 76 } 77 78 86 public void unlock() { 87 synchronized (this) { 88 if (Thread.currentThread() == _owner) { 89 if (--_count == 0) { 90 _owner = null; 91 this.notify(); 92 } 93 } else { 94 throw new IllegalMonitorStateException ( 95 "Current thread does not hold this lock"); 96 } 97 } 98 } 99 100 105 public Thread getOwner() { 106 synchronized (this) { 107 return _owner; 108 } 109 } 110 } | Popular Tags |