NinjaStars
NinjaStars

Reputation: 354

How do I respawn threads if they die

I have multiple threads of multiple types (Different classes). I want in case one of them throws an exception and dies to be replaced by another NEW thread. I am aware of the join thread function but how would I go about implementing them for 5 different type of threads such as in case type 1 thread dies is instantly replaced without having to wait for type 2 to die first.

This is some sample pseudo-code.

class1 implements runnable{
  void run(){
     try{
       while(true){
         repeat task
        }
     } catch(Exception e){
      log error
     }
  }
}


class2 implements runnable{
  void run(){
     try{
       while(true){
         repeat task
        }
     } catch(Exception e){
      log error
     }
  }
}


class3 implements runnable{
  void run(){
     try{
       while(true){
         repeat task
        }
     } catch(Exception e){
      log error
     }
  }
}

public main(){

 // start all threads .start()
}

Upvotes: 1

Views: 1679

Answers (2)

Gray
Gray

Reputation: 116888

I want in case one of them throws an exception and dies to be replaced by another NEW thread.

I don't quite understand why you can't do:

public void run() {
   // only quit the loop if the thread is interrupted
   while (!Thread.currentThread().isInterrupted()) {
      try {
         // do some stuff that might throw
         repeat task;
      } catch (Exception e) {
         // recover from the throw here but then continue running
      }
   }
}

Why do you need to restart a NEW thread? Just because a task threw an exception doesn't mean that it is somehow corrupt and it needs a fresh one to work appropriately. If you are trying to catch all exceptions (including RuntimeException) then catch (Exception e) will do this. If you want to be really careful you can even catch Throwable in case there is a chance that Errors are being generated – this is relatively rare.

If you actually have multiple tasks (or really anytime you are dealing with threads), you should consider using the ExecutorService classes. See the Java tutorial.

// create a thread pool with 10 workers
ExecutorService threadPool = Executors.newFixedThreadPool(10);
// or you can create an open-ended thread pool
// ExecutorService threadPool = Executors.newCachedThreadPool();
// define your jobs somehow
threadPool.submit(new Class1());
threadPool.submit(new Class2());
...
// once we have submitted all jobs to the thread pool, it should be shutdown
threadPool.shutdown();

So instead of forking a thread to do multiple tasks, you start a thread pool and it starts threads as necessary to accomplish a bunch of tasks. If a task fails, you could certain submit another task to the pool although that's a slightly strange pattern.

If you want to wait for all of the tasks to finish you'd use:

threadPool.awaitTermination(Long.MAX_VALUE, TimeUnit.MILLISECONDS);

Upvotes: 3

dchekmarev
dchekmarev

Reputation: 459

      boolean shouldStop() {
        // it's a good idea to think about how/when to stop ;)
        return false;
      }
      void runThreadGivenType(final Runnable taskToRun) {
        new Thread() {
          @Override
          public void run() {
            try {
              taskToRun.run();
            } finally {
              if (!shouldStop()) {
                runThreadGivenType(taskToRun);
              }
            }
          }
        }.start();
      }

      public void main(String[] args) throws Exception {
        runThreadGivenType(new Runnable() { public void run() { System.out.println("I'm almost immortal thread!"); throw new RuntimeException(); } });
        TimeUnit.SECONDS.sleep(10);
      }

and it's a good idea to think about executors to manage thread pools too. plain, [un/hand]-managed threads are not the best practice ;)

Upvotes: 1

Related Questions