【问题标题】:Timeout handler implementing Callable does not throw Exception实现 Callable 的超时处理程序不会抛出异常
【发布时间】:2013-12-21 12:04:45
【问题描述】:

我有以下两个类

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);
  }
}

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

现在我使用startTimeoutHandler() 方法启动TimeoutHandler,它应该安排未来的线程在timeoutMsec 中启动。问题是,TimeoutCallable 永远不会被调用,throw new TimeoutException(); 永远不会启动。有什么建议吗?

【问题讨论】:

    标签: java exception timeout callable


    【解决方案1】:

    我们将需要调用future.get() 来检索结果,如果提供为ExectuorException,此函数将抛出异常:可以在异常上调用getCause() 检索原因,如下所示:

         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);
          }
    

    输出:

    java.util.concurrent.TimeoutException
    

    【讨论】:

    • 什么时候调用future.get()?如果我 startTimeoutHandler() 我做一些套接字通信,如果例如nextLine() 没有响应应该抛出 TimeoutException。
    • 我猜future.get() 应该在nextLine() 函数中调用。由于您的可调用对象的结果类型为String,因此也可以通过future.get() 函数获得结果。
    • 问题是,InputStream 上的 nextLine() 是一个阻塞调用。所以我需要 TimeoutHandler 自动抛出异常。
    猜你喜欢
    • 1970-01-01
    • 2011-08-17
    • 2012-07-05
    • 2020-06-13
    • 2011-12-12
    • 2013-07-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多