1 46 package net.jforum.util.concurrent.queue; 47 48 import java.security.InvalidParameterException ; 49 import java.util.LinkedList ; 50 51 import net.jforum.util.concurrent.Queue; 52 53 56 public class UnboundedFifoQueue implements Queue 57 { 58 private final LinkedList queue = new LinkedList (); 59 60 public UnboundedFifoQueue() { } 61 62 public Object get() throws InterruptedException 63 { 64 if(Thread.interrupted()) { 65 throw new InterruptedException (); 66 } 67 68 synchronized(queue) { 69 try { 70 while(queue.isEmpty()) { 71 queue.wait(); 72 } 73 74 return queue.removeFirst(); 75 } 76 catch(InterruptedException e) { 77 queue.notify(); 78 throw e; 79 } 80 } 81 } 82 83 public Object pool(final long timeout) throws InterruptedException 84 { 85 if(Thread.interrupted()) { 86 throw new InterruptedException (); 87 } 88 89 synchronized(queue) { 90 if(!queue.isEmpty()) { 91 return queue.removeFirst(); 92 } 93 94 if(timeout <= 0) { 95 return null; 96 } 97 98 try { 99 long remaining = timeout; 100 long start = System.currentTimeMillis(); 101 102 for(;;) { 103 queue.wait(remaining); 104 105 if(!queue.isEmpty()) { 106 return queue.removeFirst(); 107 } 108 109 remaining = timeout - (System.currentTimeMillis() - start); 110 111 if(remaining <= 0) { 112 return null; 113 } 114 } 115 } 116 catch(InterruptedException e) { 117 queue.notify(); 118 throw e; 119 } 120 } 121 } 122 123 public void put(Object obj) throws InterruptedException 124 { 125 offer(obj, 0); 126 } 127 128 public boolean offer(Object obj, long timeout) throws InterruptedException 129 { 130 if(obj == null) { 131 throw new InvalidParameterException ("obj is null"); 132 } 133 134 if(Thread.interrupted()) { 135 throw new InterruptedException (); 136 } 137 138 synchronized(queue) { 139 queue.add(obj); 140 queue.notify(); 141 } 142 return true; 143 } 144 145 public int size() 146 { 147 synchronized(queue) { 148 return queue.size(); 149 } 150 } 151 } 152 | Popular Tags |