java - 通知调用方法线程中发生的异常

标签 java multithreading spring-mvc exception

我正在编写一个 Spring-mvc 应用程序。

我正在使用ThreadPoolTask​​Executor执行任务。

我有以下示例代码。

MyClass.java

public class MyClass {
    public void startProcess() {
        ThreadPoolTaskExecutor taskExecutor = //Initializing 
        for (int i = 1; i <= 5; i++) {
            taskExecutor.execute(new MyRunnable());
            // I can call taskExecutor.submit(task); also, if required
        }
    }
}

MyRunnable.java

public class MyRunnable implements Runnable {

    @Override
    public void onRun() {
        try {
            //Code which generates exception like below
            throw new Exception("Runtime Exception");
        } catch (Exception e1) {
            // log or throw the exception
        }
    }
}

我想通知 startProcess() MyRunnable 的 run 方法中发生的异常。

任何人都可以指导我吗?

我找到了以下链接,但它没有解决我的问题。

谢谢。

编辑:

还有一个问题。如果我使用 @Async 异步调用我的其他方法,并且如果我想检查异步方法中发生的异常,那么我应该做什么?因为异步方法也返回 future 对象。

我从here得到的@Async问题的答案

最佳答案

实现Callable,而不是RunnableCallable 可以抛出异常,当您使用 Future 检索 Callable 的结果时,您将得到以 ExecutionException 形式抛出的异常:

public class MyCallable implements Callable<Void> {
    public Void call() throws Exception {
        try {
            //Code which generates exception like below
            throw new Exception("Runtime Exception");
        } catch (Exception e1) {
            // log or throw the exception
        }
        return null; // To satisfy the method signature
    }
}

在我的类(class)中:

List<Future<Void>> futures = new ArrayList<>();
for (int i = 1; i <= 5; i++) {
    Future<Void> future = taskExecutor.submit(new MyCallable());
    futures.add(future);
}

// After all tasks have started, now wait for all of them to complete (they run in parallel)
// and check if there were any exceptions

for (Future<Void> future : futures) {
    try {
        future.get();
    } catch (ExecutionException e) {
        // Access the exception thrown by the different thread.
        e.getCause().printStackTrace();
    }
}

关于java - 通知调用方法线程中发生的异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27355646/

相关文章:

java - Android View 绑定(bind)。如何在 Basic Activity/Fragment 中实现绑定(bind)?

java - 音轨在 Android 中不工作

java - RxJava : How to get all results AND errors from an Observable

java - Spring MVC 和 Hibernate 集成在 intellij 中给出异常

java - Spring:同一类的多个 Controller 实例

java - Android 通话记录查询给出非法参数异常 : column '_id' does not exist

java - DataFlow 批处理作业速度慢/并行性不佳

java - Bean创建错误

java - 有效实现广度优先算法的动态队列

java - 为什么非阻塞并发优于阻塞并发