Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exception handling in ThreadPools

I have a ScheduledThreadPoolExecutor that seems to be eating Exceptions. I want my executor service to notify me if a submitted Runnable throws an exception.

For example, I'd like the code below to at the very least print the IndexArrayOutOfBoundsException's stackTrace

threadPool.scheduleAtFixedRate(   new Runnable() {     public void run() {       int[] array = new array[0];       array[42] = 5;     }   },   1000,   1500L,   TimeUnit.MILLISECONDS); 

As a side question. Is there a way to write a general try catch block for a ScheduledThreadPoolExecutor?

//////////END OF ORIGINAL QUESTION //////////////

As suggested the following Decorator works well.

public class CatcherTask implements Runnable{      Runnable runMe;      public CatcherTask(Runnable runMe) {         this.runMe = runMe;     }      public void run() {         try {             runMe.run();         } catch (Exception ex){             ex.printStackTrace();         }     } } 
like image 224
Ivan Avatar asked Oct 06 '10 18:10

Ivan


People also ask

How do you handle exceptions in thread pool?

You can subclass ScheduledThreadPoolExecutor and override the afterExecute method to handle exceptions and errors for any kind of Runnable that you submit. Show activity on this post. Consider adding a static event in your ScheduledThreadPoolExecutor class that any of your tasks can call if an exception is thrown.

What is exception handling Handling?

Exception handling is the process of responding to unwanted or unexpected events when a computer program runs. Exception handling deals with these events to avoid the program or system crashing, and without this process, exceptions would disrupt the normal operation of a program.

How do you handle exceptions in DAO layer?

don't handle any exceptions in the dao layer, instead throw it to the front-end and handle it. to handle the exception all you need to do is to catch the appropriate exception in the hierarchy and address it.


1 Answers

I wrote a small post about this problem a while ago. You have two options:

  1. Use the solution provided by Colin Herbert or
  2. use a modified version of Mark Peters solution but instead of assigning a UncaughtExceptionHandler you wrap each submitted runnable into a runnable of your own which executes (calls run) the real runnable inside a try-catch-block.

EDIT
As pointed out by Mark, it's important to wrap the Runnable passed to ScheduledExecutorService instead of the one passed to the ThreadFactory.

like image 154
whiskeysierra Avatar answered Oct 04 '22 16:10

whiskeysierra