summaryrefslogtreecommitdiff
path: root/src/main/java/bjc/esodata/DefaultSpool.java
blob: 372275d218b91741f441d60c8a4b111bb984cd22 (plain)
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
78
79
80
package bjc.esodata;

import java.util.Iterator;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.function.Consumer;

/**
 * A default implementation of {@link Spool} using a {@link LinkedBlockingDeque}
 * as the backing storage.
 * 
 * @author bjcul
 *
 * @param <T> The type contained in the spool
 */
public class DefaultSpool<T> implements Spool<T>, AutoCloseable {
	private String label;
	private String group;

	private BlockingQueue<T> container;

	private boolean closed;

	/**
	 * Create a new spool without label or group
	 */
	public DefaultSpool() {
		this(null, null);
	}

	/**
	 * Create a new spool with a given label and group.
	 * 
	 * @param label The label of the spool
	 * @param group The group for the spool
	 */
	public DefaultSpool(String label, String group) {
		this.label = label;
		this.group = group;

		this.container = new LinkedBlockingDeque<>();
		this.closed = false;
	}

	@Override
	public String label() {
		return label;
	}

	@Override
	public String group() {
		return group;
	}

	@Override
	public Consumer<T> getInput() {
		return (val) -> {
			if (closed) {
				throw new ClosedSpoolException();
			}
			container.add(val);
		};
	}

	@Override
	public Iterator<T> getOutput() {
		return container.iterator();
	}

	@Override
	public boolean isClosed() {
		return false;
	}

	@Override
	public void close() throws Exception {
		closed = true;
	}

}