blob: 80a5ebb69281615577c2888dcbca6f51607eaf03 (
plain) (
blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
|
// Copyright Vespa.ai. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.jrt;
/**
* A thread-safe queue wrapper used to pass objects between threads.
**/
class ThreadQueue
{
private Queue queue = new Queue();
private boolean closed = false;
public ThreadQueue() {}
/**
* Enqueue an object on this queue. If the queue has been closed,
* the object will not be queued, and this method will return
* false.
*
* @return true if the object was enqueued, false if this queue
* was closed
* @param obj the object to enqueue
**/
public boolean enqueue(Object obj) {
return enqueue(obj, Integer.MAX_VALUE);
}
/**
* Enqueue an object on this queue. If the queue has been closed or
* the queue already contains too many items, the object will not be
* queued, and this method will return false.
*
* @return true if the object was enqueued, false if this queue
* was closed or too large
* @param obj the object to enqueue
* @param limit more elements than this means the queue is too large
**/
public synchronized boolean enqueue(Object obj, int limit) {
if (closed || (queue.size() > limit)) {
return false;
}
queue.enqueue(obj);
if (queue.size() == 1) {
notify(); // assume only one reader
}
return true;
}
/**
* Close this queue. After this method is invoked, no more objects
* may be enqueued on this queue. Also, trying to dequeue an
* object form a queue that is both empty and closed will cause a
* {@link EndOfQueueException}.
**/
public synchronized void close() {
closed = true;
notify();
}
/**
* Dequeue the next object from this queue. This method will block
* until at least one object is available in the queue.
*
* @return the next object from the queue
* @throws EndOfQueueException if the queue is both empty and
* closed
**/
public synchronized Object dequeue() throws EndOfQueueException {
while (queue.isEmpty() && !closed) {
try { wait(); } catch (InterruptedException x) {}
}
if (queue.isEmpty()) {
throw new EndOfQueueException();
}
return queue.dequeue();
}
}
|