blob: 0f585ff30a564627c098278ae5e4c03055164cdb (
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
|
package derms.net.runicast;
import derms.net.ConcurrentDatagramSocket;
import derms.net.MessagePayload;
import derms.net.Packet;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.SocketTimeoutException;
import java.util.Queue;
import java.util.concurrent.atomic.AtomicLong;
import java.util.logging.Logger;
/** Receive acknowledgements. Remove messages from the sent queue once they are acknowledged. */
class ReceiveAcks<T extends MessagePayload> implements Runnable {
private static final int bufSize = 8192;
private final AtomicLong unacked;
private final Queue<Message<T>> sent;
private final ConcurrentDatagramSocket sock;
private final Logger log;
ReceiveAcks(AtomicLong unacked, Queue<Message<T>> sent, ConcurrentDatagramSocket sock) {
this.unacked = unacked;
this.sent = sent;
this.sock = sock;
this.log = Logger.getLogger(getClass().getName());
}
@Override
public void run() {
DatagramPacket pkt = new DatagramPacket(new byte[bufSize], bufSize);
for (;;) {
try {
sock.receive(pkt);
Ack ack = Packet.decode(pkt, Ack.class);
recvAck(ack.seq);
} catch (SocketTimeoutException e) {
if (Thread.interrupted()) {
log.info("Interrupted.");
return;
}
} catch (IOException | ClassNotFoundException | ClassCastException e) {
log.warning(e.getMessage());
}
}
}
private void recvAck(long ack) {
unacked.updateAndGet((unacked) -> {
if (ack >= unacked)
return ack+1;
return unacked;
});
while (!sent.isEmpty() && sent.peek().seq <= ack)
sent.remove();
}
}
|