[concurrency-interest] Detecting Killed Threads and Restarting them automatically

Joe Bowbeer joe.bowbeer at gmail.com
Mon Jul 3 10:38:51 EDT 2006


On 7/3/06, verma.kr at tcs.com <verma.kr at tcs.com> wrote:
>
>         I am new to concurrency field so pardon me for my ignorance.
>
>         I am trying to create a Pool of Threads using
> ScheduledThreadPoolExecutor class as follows:
>
>         ScheduledExecutorService service = new
> ScheduledThreadPoolExecutor(5)
>
>         After that i submit 5 tasks each implemeting runnable ..all these
> tasks are supposed to run infinitely in a while loop.
>
>         My doubt is that if at any stage one of the threads is killed due to
> RunTime Exception or some critical error in code being executed, then
>         is there a mechanism by which i can detect Thread termination and
> RESTART it.
>
>         If it can be automatically done that shall be great.
>
>         Please advice.
>
> Thanks And Regards,
>  Verma Rohit Kumar
>  Tata Consultancy Services Limited

I recommend that the tasks catch and handle exceptions themselves, as
David suggests.

To detect unexpected thread termination, you can (in addition)
construct your executor with a custom ThreadFactory that assigns a
custom UncaughtExceptionHandler:

  class MyThreadFactory implements ThreadFactory {
      private static final ThreadFactory defaultFactory =
              Executors.defaultThreadFactory();
      private final Thread.UncaughtExceptionHandler handler;
      MyThreadFactory(Thread.UncaughtExceptionHandler handler) {
          this.handler = handler;
      }
      public Thread newThread(Runnable r) {
          Thread t = defaultFactory.newThread(r);
          t.setUncaughtExceptionHandler(handler);
          return t;
      }
  };

  ThreadFactory factory = new MyThreadFactory(handler);
  ScheduledExecutorService service =
Executors.newScheduledThreadPool(5, factory);


More information about the Concurrency-interest mailing list