-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSequenceBuffer.java
More file actions
55 lines (47 loc) · 1.9 KB
/
Copy pathSequenceBuffer.java
File metadata and controls
55 lines (47 loc) · 1.9 KB
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
import java.util.TreeMap;
import java.util.concurrent.BlockingQueue;
import java.util.function.Consumer;
public class SequenceBuffer {
private static final long GAP_TIMEOUT_MS = 100; // skip gap after 100ms
private final TreeMap<Integer, Order> buffer = new TreeMap<>();
private final BlockingQueue<Order> outputQueue;
private int nextExpected = 1;
private long gapDetectedAt = -1;
public SequenceBuffer(BlockingQueue<Order> outputQueue) {
this.outputQueue = outputQueue;
}
public synchronized void add(Order order) throws InterruptedException {
if (order.getSequenceId() < nextExpected) {
// Duplicate or very late order — discard
return;
}
buffer.put(order.getSequenceId(), order);
flush();
}
private void flush() throws InterruptedException {
while (!buffer.isEmpty()) {
int firstKey = buffer.firstKey();
if (firstKey == nextExpected) {
// In-order: release it
outputQueue.put(buffer.remove(firstKey));
nextExpected++;
gapDetectedAt = -1; // reset gap timer
} else {
// Gap detected — start or check timeout
long now = System.currentTimeMillis();
if (gapDetectedAt == -1) {
gapDetectedAt = now; // start the clock
} else if (now - gapDetectedAt > GAP_TIMEOUT_MS) {
// Timeout: skip the missing sequence ID
System.out.printf("[SeqBuffer] Skipping missing seqId=%d after timeout%n",
nextExpected);
nextExpected++;
gapDetectedAt = -1;
// Loop again to try the next one
continue;
}
break; // wait for the missing order
}
}
}
}