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?
As I see it, you have 2 options:
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)