简体   繁体   中英

Where to perform final cleanup for a scheduled task when using a ScheduledExecutorService

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:

  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 (ie if you have a persistent connection or you create one per request)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM