java - 在 java 中调用超时的阻塞方法调用

标签 java java.util.concurrent concurrent-programming

我想在 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() 抛出一些异常,我该如何在外部类中捕获它们?

最佳答案

您已在您提供的代码中设置了执行此操作的所有内容。只需更换

// handle other exceptions

用你的异常处理。
如果您需要获取特定的 Exception,您可以通过以下方式获取它:

Throwable t = e.getCause();

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

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

关于java - 在 java 中调用超时的阻塞方法调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11362823/

相关文章:

java - 从循环中获取数组元素

java - 从一组文件中删除一些特定字符

java - 重复算法问题,Java

java - 带有 Scala IO 实现的 JVM 上的光纤

java - 在碰撞检测中获取 java.util.ConcurrentModificationError

Web 应用程序中的 Java 并发多线程算法 - 比预期慢

java - 如何在Java中实现二进制信号量类?

java - Java 中的原子是保证顺序还是仅保证唯一性?

c# - List<T> 的线程安全,只有一个 Writer,没有 Enumerators

go - throw 所有的 goroutines 都睡着了——僵局! ------- 谷歌GO的错误