Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use ExecutorService to handle an aborted Runnable?

I have a Worker class that implements Runnable and has a run() method which may raise exceptions in the event of a conflict, and return early. When it does, that thread needs to be put back into the queue to be run again.

From looking at this question, it seems I need to rewrite with Callable. Is that correct? There's no way to do this with Runnable?

like image 229
temporary_user_name Avatar asked Dec 10 '12 22:12

temporary_user_name


2 Answers

Well you can have the worker thread do it itself. If you have control of the executor.

class RequeableWorker implement Runnable{
  private final ExecutorService e;
  public RequeableWorker(ExecutorService e){this.e =e;}

  public void run(){
     try{
        //do work
     }catch(RuntimeException ex){
        e.submit(this);
        throw ex;
     }
  }
}

Or as your answer suggests having the waiting thread of a Future re-queue.

public void workOrRequeue(){
    for(;;){
       Future<?> future = e.submit(someCallable());
       try{
          future.get();
          return;
       }catch(ExecutionException ex){
          //maybe log, ex.printStackTrace();
       }
    }
}
like image 138
John Vint Avatar answered Oct 20 '22 20:10

John Vint


As say the docs for Future.get():

Throws:

[...]

ExecutionException - if the computation threw an exception

like image 40
millimoose Avatar answered Oct 20 '22 18:10

millimoose