KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > oddjob > util > BlockingQueue


1 /*
2  * Copyright 2004, Rob Gordon.
3  */

4 package org.oddjob.util;
5
6 import java.util.LinkedList JavaDoc;
7
8 /**
9  *
10  * @author Rob Gordon.
11  */

12 public class BlockingQueue {
13
14     private final LinkedList JavaDoc list = new LinkedList JavaDoc();
15     private boolean closed = false;
16     private boolean wait = false;
17     
18     synchronized public void enqueue(Object JavaDoc o) {
19         if (closed) {
20             throw new ClosedException();
21         }
22         list.add(o);
23         notify();
24     }
25
26     synchronized public Object JavaDoc dequeue() {
27         while (!closed && list.size() == 0) {
28             try {
29                 wait();
30             }
31             catch (InterruptedException JavaDoc e) {
32                 // ignore
33
}
34         }
35         if (list.size() == 0) {
36             return null;
37         }
38         return list.removeFirst();
39     }
40     
41     synchronized public int size() {
42         return list.size();
43     }
44     
45     synchronized public void close() {
46         closed = true;
47         notifyAll();
48     }
49     
50     synchronized public void open() {
51         closed = false;
52     }
53     
54     public static class ClosedException extends RuntimeException JavaDoc {
55         ClosedException() {
56             super("Queue closed.");
57         }
58     }
59 }
60
Popular Tags