I need to execute a task using any Executor
or ExecutorService
. The task (Callable
or Runnable
) is supposed to run infinitely, but in case of any exception it should be rethrown to the thread that submitted the task.
I know that future.get()
would throw ExecutionException
for me:
ExecutorService executor = Executors.newSingleThreadExecutor();
Future<?> future = executor.submit(new Task());
future.get();
However, in sunny day scenario I block on future.get()
indefinitely, so I cannot use it.
Is it possible to have any Executor
that simply throws exception when underlying task fails?
I don't think it is possible to do this with simply using Executors.
You can consider using a try-catch block in your Task and add the exception on to a queue in the catch block.
try{
//perform task
}catch(Exception e){
queue.offer(e)
}
Create a thread that reads the exception from the queue.
public void run() {
Exception e;
try {
e = q.take();
e.printStackTrace();
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
}
}