Timeout handler implementing Callable does not throw Exception

244 views Asked by At

I have the following two classes

public class TimeoutHandler
{
  private int timeoutMsec = 10000;
  private ScheduledExecutorService scheduler;
  private ScheduledFuture<String> future;

  public TimeoutHandler()
  {
  }

  public TimeoutHandler(int msec)
  {
    timeoutMsec = msec;
  }

  public void startTimeoutHandler() throws TimeoutException
  {
    scheduler = Executors.newScheduledThreadPool(1);
    future = scheduler.schedule(new TimeoutCallable(), timeoutMsec, TimeUnit.MILLISECONDS);
  }
}

and

public class TimeoutCallable implements Callable<String>
{
  @Override
  public String call() throws TimeoutException
  {
    throw new TimeoutException();
  }
}

Now I start the TimeoutHandler with the method startTimeoutHandler() and it should schedule a future thread to start in timeoutMsec. The problem is, that the TimeoutCallable is never called and the throw new TimeoutException(); is never launched. Any suggestions?

1

There are 1 answers

3
Sage On

We will need to call future.get() to retrieve the result and this function will throw the exception if provided as a ExectuorException: the cause can be retrieved invoking the getCause() on the exception as shown below:

     try {
          future.get();
      } catch (InterruptedException ex) {
          Logger.getLogger(CallableTest.class.getName()).log(Level.SEVERE, null, ex);
      } catch (ExecutionException ex) {
          System.out.println(ex.getCause());
          //Logger.getLogger(CallableTest.class.getName()).log(Level.SEVERE, null, ex);
      }

Output:

java.util.concurrent.TimeoutException