KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > ziclix > python > sql > util > Queue


1 /*
2  * Jython Database Specification API 2.0
3  *
4  * $Id: Queue.java,v 1.2 2005/02/23 04:26:21 bzimmer Exp $
5  *
6  * Copyright (c) 2001 brian zimmer <bzimmer@ziclix.com>
7  *
8  */

9 package com.ziclix.python.sql.util;
10
11 import java.util.LinkedList JavaDoc;
12
13 /**
14  * This queue blocks until closed or an element is enqueued. If the queue
15  * reaches capacity, the dequeue thread gets priority in order to bring the
16  * queue size under a certain threshold.
17  *
18  * @author brian zimmer
19  * @version $Revision: 1.2 $
20  */

21 public class Queue {
22
23     /**
24      * Field closed
25      */

26     protected boolean closed;
27
28     /**
29      * Field queue
30      */

31     protected LinkedList JavaDoc queue;
32
33     /**
34      * Field capacity, threshold
35      */

36     protected int capacity, threshold;
37
38     /**
39      * Instantiate a blocking queue with no bounded capacity.
40      */

41     public Queue() {
42         this(0);
43     }
44
45     /**
46      * Instantiate a blocking queue with the specified capacity.
47      */

48     public Queue(int capacity) {
49
50         this.closed = false;
51         this.capacity = capacity;
52         this.queue = new LinkedList JavaDoc();
53         this.threshold = (int) (this.capacity * 0.75f);
54     }
55
56     /**
57      * Enqueue an object and notify all waiting Threads.
58      */

59     public synchronized void enqueue(Object JavaDoc element) throws InterruptedException JavaDoc {
60
61         if (closed) {
62             throw new QueueClosedException();
63         }
64
65         this.queue.addLast(element);
66         this.notify();
67
68         /*
69          * Block while the capacity of the queue has been breached.
70          */

71         while ((this.capacity > 0) && (this.queue.size() >= this.capacity)) {
72             this.wait();
73
74             if (closed) {
75                 throw new QueueClosedException();
76             }
77         }
78     }
79
80     /**
81      * Blocks until an object is dequeued or the queue is closed.
82      */

83     public synchronized Object JavaDoc dequeue() throws InterruptedException JavaDoc {
84
85         while (this.queue.size() <= 0) {
86             this.wait();
87
88             if (closed) {
89                 throw new QueueClosedException();
90             }
91         }
92
93         Object JavaDoc object = this.queue.removeFirst();
94
95         // if space exists, notify the other threads
96
if (this.queue.size() < this.threshold) {
97             this.notify();
98         }
99
100         return object;
101     }
102
103     /**
104      * Close the queue and notify all waiting Threads.
105      */

106     public synchronized void close() {
107
108         this.closed = true;
109
110         this.notifyAll();
111     }
112 }
113
Popular Tags