[concurrency-interest] Unreported RuntimeException if Future.get() is never invoked

Joe Bowbeer joe.bowbeer at gmail.com
Fri Dec 22 03:20:16 EST 2006


Based on the snippet you provided, it may be simpler to extend
FutureTask at the outer level:

public class MyTask<V> extends FutureTask<V> {
  public void execute() {
    exec.execute(this);
  }
  protected void done() {
    // log failures here...
  }
}


On 12/21/06, Kevin Condon <conivek at gmail.com> wrote:
>
> There are a variety of reasons that you want a Future but may never
> invoke get().  One situation where this could happen is a concurrent
> task with a cancel option, so you only need the Future for the cancel.
>  Here is a skeleton example:
>
> public class CancellableTask implements Runnable {
>   private final ExecutorService exec;
>   private volatile Future<?> future = null;
>
>   public CancellableTask(ExecutorService exec) {
>     this.exec = exec;
>   }
>
>   public void execute() {
>     // example ignores race on future for concurrent task executions
>     future = exec.submit(this);
>   }
>
>   public void cancel() {
>     if (future != null) {
>       future.cancel(true);
>     }
>   }
>
>   public void run() {
>     boolean error = false;
>     // work to be done ...
>     if (error) {
>       // this will not be logged!!!!
>       throw IllegalStateException("Secret exception");
>     }
>   }
> }
>
> A co-worker and I, JCiP in hand, discovered that the solution to this
> is to extend FutureTask overriding the done() hook to check/log the
> exception and then use exec.execute(futureTask) instead of
> submit(this).  To do this, change the execute() method:
>
>   public void execute() {
>     FutureTask<?> futureTask = new FutureTask<?>(this, null) {
>       protected void done() {
>         try {
>           get();
>         } catch (ExecutionException ex) {
>           ex.getCause().printStackTrace();
>         } catch (CancellationException ex) {
>           // ignore unless you want to log task cancellation here
>         } catch (InterruptedException ex) {
>           // ignore; we're done, so get() won't block or be interrupted
>         }
>       }
>     };
>     future = futureTask;
>     exec.execute(futureTask);
>   }
>


More information about the Concurrency-interest mailing list