我正在编写一个 Spring-mvc 应用程序。
我正在使用ThreadPoolTaskExecutor
执行任务。
我有以下示例代码。
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 方法中发生的异常。
任何人都可以指导我吗?
我找到了以下链接,但它没有解决我的问题。
- Handling exceptions from Java ExecutorService tasks
- http://java.dzone.com/articles/spring-async-and-exception
谢谢。
编辑:
还有一个问题。如果我使用 @Async 异步调用我的其他方法,并且如果我想检查异步方法中发生的异常,那么我应该做什么?因为异步方法也返回 future 对象。
我从here得到的@Async问题的答案
最佳答案
实现Callable
,而不是Runnable
。 Callable
可以抛出异常,当您使用 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/