1 /**
2 * .
3 * Copyright � 1999 Erich P G.
4 *
5 */
6
7 package autohit.utils;
8
9 import java.util.Vector;
10
11 /**
12 * A locked queue. This will allow one thread to safely enqueue
13 * objects for other threads. All of the methods are thread-safe.
14 *
15 * @author Erich P. Gatejen
16 * @version 1.0
17 * <i>Version History</i>
18 * <code>EPG - Initial - 15Jan99</code>
19 *
20 */
21 public class LockedQueue {
22
23 // --- FINAL FIELDS ------------------------------------------------------
24
25 // --- FIELDS ------------------------------------------------------------
26
27 /**
28 * The object monitor for the queue.
29 *
30 * @see autohit.utils.ObjectMonitor
31 */
32 private ObjectMonitor myLock;
33
34 /**
35 * The actual queue.
36 */
37 private Vector queue;
38
39 /**
40 * The queue size. Using this instead of Vector.size() so
41 * that polling is faster.
42 */
43 private int queueSize;
44
45 /**
46 * Constructor.
47 */
48 public LockedQueue() {
49 myLock = new ObjectMonitor();
50 queue = new Vector();
51 queueSize = 0;
52 }
53
54 /**
55 * Get an object from the queue. This method will block
56 * if other threads are enqueuing items, so watch out in
57 * 'real-time' threads.
58 *
59 * @return an Object reference or null if the queue is empty.
60 */
61 public Object get() {
62
63 Object c = null;
64
65 // blocks until a message arrives
66 myLock.lock(true);
67 if (!queue.isEmpty()) {
68 c = (Object) queue.elementAt(0);
69 queue.removeElementAt(0);
70 queueSize--;
71 }
72 myLock.lock(false);
73 return c;
74 }
75
76 /**
77 * Put an object in the queue.
78 *
79 * @param c the object to enqueue.
80 */
81 public void put(Object c) {
82
83 myLock.lock(true);
84 queue.addElement(c);
85 queueSize++;
86 myLock.lock(false);
87 block(false);
88 }
89
90 /**
91 * Asks if the queue has any objects.
92 *
93 * @return true if there is an object in the queue,
94 * otherwise false.
95 */
96 public boolean hasObject() {
97 if (queueSize > 0) return true;
98 else return false;
99 }
100
101 /**
102 * Blocks until an object is enqueued by another thread.
103 * Being released fromt he block is no guarentee that an object
104 * available for the thread, if it is possible for another
105 * thread to swoop in an unenqueue one.
106 *
107 * @param set pass true to block. Passing false will
108 * unblock any waiting threads, so be careful!
109 */
110 public synchronized void block(boolean set) {
111
112 // Kinda a hack. set=true means block on this object
113 // set = false means release the block
114 // put automatically calls this with false to release it.
115
116 if (set == true) {
117 try {
118 wait();
119 } catch (InterruptedException e) {}
120
121 } else {
122 notifyAll();
123 }
124 }
125
126 }
|