summaryrefslogtreecommitdiffstats
path: root/src/main/java/derms/net/rmulticast/Announce.java
blob: 08d817d70f6a1dae02d7d6b4d53f26895e416810 (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
package derms.net.rmulticast;

import derms.net.ConcurrentMulticastSocket;
import derms.net.Packet;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.time.Duration;
import java.util.logging.Logger;

/**
 * Periodically announce the presence of the local process to the group.
 * Allows processes to populate their set of group members, even if not
 * all members would normally send messages to the group.
 */
class Announce implements Runnable {
    private static final Duration period = Duration.ofSeconds(30);

    private final DatagramPacket pkt;
    private final ConcurrentMulticastSocket outSock;
    private final Logger log;

    Announce(InetSocketAddress group, InetAddress laddr, ConcurrentMulticastSocket outSock) throws IOException {
        AnnounceMessage msg = new AnnounceMessage(laddr);
        this.pkt = Packet.encode(msg, group);
        this.outSock = outSock;
        this.log = Logger.getLogger(this.getClass().getName());
    }

    @Override
    public void run() {
        try {
            for (;;) {
                try {
                    Wait.forDuration(period);
                    outSock.send(pkt);
                } catch (IOException e) {
                    log.warning(e.getMessage());
                }
            }
        } catch (InterruptedException e) {
            log.info("Announce thread interrupted: " + e.getMessage());
        }
    }
}