1 11 12 package org.apache.beehive.netui.util.internal.concurrent; 13 14 import java.util.*; 15 16 class CondVar implements Condition, java.io.Serializable { 17 18 19 protected final LockInfo lock; 20 21 26 27 CondVar(LockInfo lock) { 28 this.lock = lock; 29 } 30 31 public void awaitUninterruptibly() { 32 boolean wasInterrupted = false; 33 while (true) { 34 try { 35 await(); 36 if (wasInterrupted) { 37 Thread.currentThread().interrupt(); 38 } 39 return; 40 } 41 catch (InterruptedException e) { 42 wasInterrupted = true; 43 } 44 } 45 } 46 47 public void await() throws InterruptedException { 48 if (Thread.interrupted()) 49 throw new InterruptedException (); 50 try { 51 synchronized (this) { 52 lock.unlock(); 53 try { 54 wait(); 55 } 56 catch (InterruptedException ex) { 57 notify(); 58 throw ex; 59 } 60 } 61 } 62 finally { 63 lock.lock(); 64 } 65 } 66 67 public boolean await(long timeout, TimeUnit unit) throws InterruptedException { 68 if (Thread.interrupted()) throw new InterruptedException (); 69 long nanos = unit.toNanos(timeout); 70 boolean success = false; 71 try { 72 synchronized (this) { 73 lock.unlock(); 74 try { 75 if (nanos > 0) { 76 long start = Utils.nanoTime(); 77 TimeUnit.NANOSECONDS.timedWait(this, nanos); 78 success = Utils.nanoTime() - start < nanos; 82 } 83 } 84 catch (InterruptedException ex) { 85 notify(); 86 throw ex; 87 } 88 } 89 } 90 finally { 91 lock.lock(); 92 } 93 return success; 94 } 95 96 public boolean awaitUntil(Date deadline) throws InterruptedException { 101 if (deadline == null) throw new NullPointerException (); 102 long abstime = deadline.getTime(); 103 if (Thread.interrupted()) throw new InterruptedException (); 104 105 boolean success = false; 106 try { 107 synchronized (this) { 108 lock.unlock(); 109 try { 110 long start = System.currentTimeMillis(); 111 long msecs = abstime - start; 112 if (msecs > 0) { 113 wait(msecs); 114 success = System.currentTimeMillis() - start < msecs; 118 } 119 } 120 catch (InterruptedException ex) { 121 notify(); 122 throw ex; 123 } 124 } 125 } 126 finally { 127 lock.lock(); 128 } 129 return success; 130 } 131 132 public synchronized void signal() { 133 if (!lock.isHeldByCurrentThread()) { 134 throw new IllegalMonitorStateException (); 135 } 136 notify(); 137 } 138 139 public synchronized void signalAll() { 140 if (!lock.isHeldByCurrentThread()) { 141 throw new IllegalMonitorStateException (); 142 } 143 notifyAll(); 144 } 145 146 static interface LockInfo extends Lock { 147 boolean isHeldByCurrentThread(); 148 } 149 } 150 | Popular Tags |