Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 618
Herr Derb Avatar asked Oct 26 '25 08:10

Herr Derb


1 Answers

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":

  • ThreadPoolExecutor.AbortPolicy (the default)
  • ThreadPoolExecutor.CallerRunsPolicy ( runs the Task on the Thread that called execute, blocking it, of course )
  • ThreadPoolExecutor.DiscardPolicy ( discards the Task that has been rejected )
  • ThreadPoolExecutor.DiscardOldestPolicy ( adds the rejected task to the queue and discards the oldest task in the queue instead )

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.

like image 187
Fildor Avatar answered Oct 27 '25 21:10

Fildor



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!