Question

The assignment is to implement a very very simplified computing "cloud". The cloud instances ("engines") are supposed to regularly send keep-alive messages ("commands") to a supervisor. I've implemented this using the following task:

public class KeepAlive implements Runnable {
    Engine engine;
    DatagramSocket sock;

    public KeepAlive(Engine engine) {
        this.engine = engine;
        sock = new DatagramSocket();
    }

    public void run() {
        DatagramSocket sock = null;

        EngineArguments args = engine.getArgs();

        KeepAliveCommand cmd = new KeepAliveCommand(…);
        byte[] data = cmd.toString().getBytes("UTF-8");
        DatagramPacket p = new DatagramPacket(data, data.length, InetAddress.getByName(args.getSchedulerHost()), args.getSchedulerPort());
        sock.send(p);
    }    
}

that is scheduled for execution using scheduleAtFixedRate(). I'm doing a graceful (ish) shutdown of using shutdownNow() to avoid having to keep explicit references to long-running tasks.

Is there any "clean" way to perform cleanup specific to the task (closing the DatagramSocket)? Alternately, does it even make sense to keep a DatagramSocket instance between scheduled runs or can I just create a new one every time?

Was it helpful?

Solution

As I see it, you have 2 options:

  1. Keep track of the sockets within a "Socket Pool" and using a "send" method of this pool. Then, after you shutdown the executor you shutdown the Pool
  2. Extend ScheduledThreadPoolExecutor, which can be a little more difficult. But, the API is clean... Notice that you can "decorate" the tasks, also there is a "termintated" method.

I like the idea of the "socket pool". Then, how the connection are handled is up to the pool (i.e. if you have a persistent connection or you create one per request)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top