/
Consumer.java
47 lines (38 loc) · 902 Bytes
/
Consumer.java
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
package de.grundid.twiki.parser.consumer;
import java.util.concurrent.BlockingQueue;
public abstract class Consumer<T> implements Runnable {
private BlockingQueue<T> queue;
private boolean finishWhenDone;
protected abstract void consume(T element);
/**
* This method is called at the end of the consume loop. Override this if you need to flush any batches.
*/
protected void finishConsuming() {
}
public void setQueue(BlockingQueue<T> queue) {
this.queue = queue;
}
@Override
public void run() {
try {
while (!Thread.interrupted()) {
if (queue.isEmpty() && finishWhenDone)
break;
else
Thread.sleep(10);
while (!queue.isEmpty()) {
consume(queue.take());
}
}
}
catch (InterruptedException ex) {
}
finishConsuming();
synchronized (this) {
notifyAll();
}
}
public void producerFinished() {
this.finishWhenDone = true;
}
}