1 13 14 package org.apache.beehive.netui.util.internal.concurrent; 15 16 import java.util.*; 17 18 23 24 abstract class WaitQueue { 25 26 public abstract void insert(WaitNode w); public abstract WaitNode extract(); 29 public abstract boolean hasNodes(); 30 public abstract int getLength(); 31 public abstract Collection getWaitingThreads(); 32 public abstract boolean isWaiting(Thread thread); 33 34 static interface QueuedSync { 35 boolean recheck(WaitNode node); 37 void takeOver(WaitNode node); 39 } 40 41 static class WaitNode { 42 boolean waiting = true; 43 WaitNode next = null; 44 final Thread owner; 45 46 public WaitNode() { 47 this.owner = Thread.currentThread(); 48 } 49 50 public Thread getOwner() { 51 return owner; 52 } 53 54 public synchronized boolean signal(QueuedSync sync) { 55 boolean signalled = waiting; 56 if (signalled) { 57 waiting = false; 58 notify(); 59 sync.takeOver(this); 60 } 61 return signalled; 62 } 63 64 public synchronized boolean doTimedWait(QueuedSync sync, long nanos) 65 throws InterruptedException 66 { 67 if (sync.recheck(this) || !waiting) 68 return true; 69 else if (nanos <= 0) { 70 waiting = false; 71 return false; 72 } 73 else { 74 long deadline = Utils.nanoTime() + nanos; 75 try { 76 for (; ; ) { 77 TimeUnit.NANOSECONDS.timedWait(this, nanos); 78 if (!waiting) return true; 80 else { 81 nanos = deadline - Utils.nanoTime(); 82 if (nanos <= 0) { waiting = false; 84 return false; 85 } 86 } 87 } 88 } 89 catch (InterruptedException ex) { 90 if (waiting) { waiting = false; throw ex; 93 } 94 else { Thread.currentThread().interrupt(); 96 return true; 97 } 98 } 99 } 100 } 101 102 public synchronized void doWait(QueuedSync sync) 103 throws InterruptedException 104 { 105 if (!sync.recheck(this)) { 106 try { 107 while (waiting) wait(); 108 } 109 catch (InterruptedException ex) { 110 if (waiting) { waiting = false; throw ex; 113 } 114 else { Thread.currentThread().interrupt(); 116 return; 117 } 118 } 119 } 120 } 121 } 122 123 } 124 125 | Popular Tags |