Is catching Java Throwable best way to restart thread

  • A+
Category:Languages

I have following code in java-

@Override public void run() {      logger.info("Thread Started:" + this.getName());      try {         runJob();     } catch( Throwable e) {         logger.error("Exception in running thread: " + this.getName() + ", restarting job", e);         run();     } }  public void runJob() {      while(true) {        try {            // Work here        } catch(Exception e) {            // log the exception        }     }  } 

Is this code actually be going to keep the thread alive in every case and is this only the way to recover thread?

This is the alternative I thought of after reading all the answers. Let me know if this is a good way for keeping the thread alive forever even if Error occurred:

@Override public void run() {      logger.info("Thread Started:" + this.getName());      while(true) {       try {         runJob();       } catch( Throwable e) {         logger.error("Exception in running thread: " + this.getName() + ", restarting job", e);         }     } }  public void runJob() {       try {           // Work here      } catch(Exception e) {           // log the exception      }  } 


This has little to do with "threads". Retry logic can be implemented on exceptions, and that's common practice.

However, catching Throwable is clearly a dangerous thing to do. You would want to retry on select errors (such as timeout, failed connection, etc), which of course requires finer knowledge of how your runJob() method runs.

Beside that, your retry implementation is making a recursive call which can also be bad. You'll end up running into a stack overflow error (and also catch it with your Throwbale catch block, altogether leading to weird behavior). Rather loop and execute runJob() repeatedly.

boolean retry = false; do {     try {         runJob();         retry = false;     } catch (SpecificException e) { //timeout, network failure exceptions         logger.error("Exception in running thread: "             + this.getName() + ", restarting job");         retry = true;     } } while(retry); 

You may also need to add a counter to limit the number of retries.

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: