【问题标题】:calling a blocking method call with timeout in java在java中调用带有超时的阻塞方法调用
【发布时间】:2012-07-06 13:08:43
【问题描述】:

我想在 java 中调用一个由于某种原因而阻塞的方法。我想等待该方法 X 分钟,然后我想停止该方法。

我在 StackOverflow 上阅读了一个解决方案,它让我快速入门。我在这里写:-

ExecutorService executor = Executors.newCachedThreadPool();
    Callable<Object> task = new Callable<Object>() {
       public Object call() {
          return something.blockingMethod();
       }
    };
    Future<Object> future = executor.submit(task);
    try {
       Object result = future.get(5, TimeUnit.SECONDS); 
    } catch (TimeoutException ex) {
       // handle the timeout
    } catch (InterruptedException e) {
       // handle the interrupts
    } catch (ExecutionException e) {
       // handle other exceptions
    } finally {
       future.cancel(); // may or may not desire this
    }

但是现在我的问题是,我的函数可以抛出一些异常,我必须捕获并相应地执行一些任务。因此,如果在代码中,blockingMethod() 函数引发了一些异常,我如何在 Outer 类中捕获它们?

【问题讨论】:

  • 我会在匿名类中抓住它。这样就没有异常可以捕获。
  • 另外,不要显式捕获每个检查的异常,因为您可能不会编写任何特定的处理代码。写catch (RuntimeException e) { throw e; } catch (Exception e) { throw new RuntimeException(e); }
  • 是的 早些时候我也想过同样的事情,我会这样做,但是我想在异常处理代码中使用很多外部类的变量。而且我无法在 Inner 类中访问这些变量。

标签: java java.util.concurrent concurrent-programming


【解决方案1】:

您已在提供的代码中进行了所有设置。直接替换

// handle other exceptions

您的异常处理。
如果您需要获取特定的Exception,请使用:

Throwable t = e.getCause();

为了区分您的异常,您可以这样做:

if (t instanceof MyException1) {
  ...
} else if (t instanceof MyException2) {
  ...
...

【讨论】:

  • 我不知道我肯定会这样做:) 还有一个问题,如果我有不同类型的异常,例如 MyException1、MyException2,我必须根据不同的异常进行不同的处理。如何区分多个异常?
【解决方案2】:

我想在ExecutionException 实例中的cause 中。

【讨论】:

    【解决方案3】:

    ExecutionException 捕获块中:e.getCause()

    https://docs.oracle.com/javase/6/docs/api/java/lang/Throwable.html#getCause

    【讨论】:

      【解决方案4】:

      thread.sleep(x millisecods) 将停止线程 x 毫秒,然后它将恢复。另一种方法是调用 thread.wait(x)(x 具有超时值),然后调用 thread.notify() 以“唤醒”睡眠线程。

      【讨论】:

        猜你喜欢
        • 2023-03-31
        • 2013-11-16
        • 1970-01-01
        • 2020-01-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-12-26
        • 2020-04-22
        相关资源
        最近更新 更多