Source code: org/altara/util/Queue.java
1 /* Altara Utility Classes
2 Copyright (c) 2001,2002 Brian H. Trammell
3
4 This library is free software; you can redistribute it and/or
5 modify it under the terms of the GNU Lesser General Public
6 License as published by the Free Software Foundation; either
7 version 2.1 of the License, or (at your option) any later version.
8
9 This library is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 Lesser General Public License for more details.
13
14 You should have received a copy of the GNU Lesser General Public
15 License along with this library; if not, it is available at
16 http://www.gnu.org/copyleft/lesser.html, or by writing to the
17 Free Software Foundation, Inc., 59 Temple Place, Suite 330,
18 Boston, MA 02111-1307 USA
19 */
20
21 package org.altara.util;
22
23 import java.io.*;
24 import java.util.*;
25
26 /** Queue is a wrapper around a LinkedList providing a queue-oriented
27 view.
28 */
29
30 public class Queue {
31
32 LinkedList list;
33 boolean isLocked;
34
35 public Queue() {
36 list = new LinkedList();
37 }
38
39 /** Lock the queue. A locked queue may not be dequeued from - i.e. it
40 will block as if it is empty even when it is full. Locking has
41 no effect on nb_dequeue().
42 */
43
44 public synchronized void lock() {
45 this.isLocked = true;
46 }
47
48 /** Unlock the queue. Reverses the effect of a previous lock().
49 */
50
51 public synchronized void unlock() {
52 this.isLocked = false;
53 notify();
54 }
55
56 /** Flush the queue. Removes all elements from the queue.
57 */
58
59 public synchronized void flush() {
60 list.clear();
61 }
62
63 /** Enqueue an object. This will place the object into the queue for
64 later in-order dequeueing.
65
66 @param obj the object to enqueue.
67 */
68
69 public synchronized void enqueue(Object obj) {
70 list.addFirst(obj);
71 notify();
72 }
73
74 /** Retrieve the next object from the queue. This method will
75 block if the queue is empty.
76
77 @throws InterruptedException if the method blocked on an empty queue
78 and was subsequently interrupted.
79 @return the next object from the queue.
80 */
81
82 public synchronized Object dequeue() throws InterruptedException {
83 while (list.size() == 0 || isLocked)
84 wait();
85 return nb_dequeue();
86 }
87
88 /** Retrieve the next object from the queue. This method will return null
89 if the queue is empty.
90
91 @return the next object from the queue, or null if none exists.
92 */
93
94 public synchronized Object nb_dequeue() {
95 if (list.size() == 0) return null;
96 return list.removeLast();
97 }
98
99 /** Return this queue's size.
100
101 @return this queue's size.
102 */
103
104 public int size() {
105 return list.size();
106 }
107 }