Search code examples
javajava.util.concurrentscheduledexecutorservice

ScheduledExecutorService: How do I catch its exceptions?


I'm currently working with an ScheduledExecutorService. I use it this way:

ScheduledExecutorService executor;
public class ScheduledFanSpeedController implements Runnable {
.
.
.
public void start(){
executor = Executors.newScheduledThreadPool(1);
executor.scheduleAtFixedRate(this, 0, 55, TimeUnit.SECONDS);
}

The .scheduleAtFixRate may throw a RejectedExecutionException. How or/and where would I catch this exception when it gets thrown on the n-th run of the task by the executor? Do I really have to mess with overriding for that?


Solution

  • You can use this Constructor to inject your own implementation of a RejectedExecutionHandler:

    public ScheduledThreadPoolExecutor(int corePoolSize, RejectedExecutionHandler handler)

    So you would instead of using executor = Executors.newScheduledThreadPool(1); write:

    executor = new ScheduledThreadPoolExecutor(1, new MyRejectedHandler());
    

    where MyRejectedHandler would be an instance of your implementation of the interface RejectedExecutionHandler.

    I used this once to handle congestion.

    There are also predefined "policies":

    You would set them like this:

    executor = new ScheduledThreadPoolExecutor(1, new ThreadPoolExecutor.DiscardOldestPolicy());
    

    Do I really have to mess with overriding for that?

    Not sure what you mean by that. But if you thought you have to extend ThreadPoolExecutor, then in most cases : no. That Family of classes is IMHO so neatly designed and complete that you nearly never have the urge to do that. It is almost like a construction kit which allows for a vast variety of behaviors. The most invasive implementation I had to do once was to inject my own ThreadFactory (for thread naming) and a RejectedExecutionHandler that removed optional low-prio tasks from the queue on congestion.

    Other Exceptions

    If you want to catch Exceptions that arise inside the run method, then I suggest you enclose the body of it in try/catch. Which is ok for first shot. I tend to narrow down try/catch blocks to where they are really needed. This enables you to handle them on the executing Thread of the pool.