在并发编程中在执行java.util.concurrent.Future实现类的get方法时,需要捕获java.util.concurrent.ExecutionException这个异常。Future.get()方法通常是要获取任务的执行结果,当执行任务的过程中抛出了异常,就会产生ExecutionException异常。
案例分析:
package threadpool;
import org.junit.Test;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.*;
public class ExecutorCompletionServiceDemo {
@Test
public void TestExecutorCompletionService () throws InterruptedException {
ThreadPoolExecutor executor = new ThreadPoolExecutor(10, 20, 1, TimeUnit.SECONDS, new ArrayBlockingQueue<>(50));
Collection<Callable<String>> tasks = new ArrayList<>();
tasks.add(() -> {return "1";});
tasks.add(() -> {return "2";});
tasks.add(() -> {return "3";});
tasks.add(() -> {return "4";});
tasks.add(() -> {return "5";});
tasks.add(() -> {return "6";});
tasks.add(() -> {return "7";});
tasks.add(() -> {return "8";});
tasks.add(() -> {throw new UnsupportedOperationException("暂不支持该操作");});
tasks.add(() -> {throw new NullPointerException("NullPointerException occurred");});
execute(executor, tasks);
}
private static void execute(ThreadPoolExecutor executor, Collection<Callable<String>> tasks) {
CompletionService<String> completionService = new ExecutorCompletionService<>(executor);
List<Future<String>> futures = new ArrayList<>(tasks.size());
for (Callable<String> task : tasks) {
futures.add(completionService.submit(task));
}
for (int i = 0; i < futures.size(); i++) {
try {
Future<String> take = completionService.take();
String s = take.get();
System.out.println(s);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new RuntimeException(e);
} catch (ExecutionException e) {
throw new RuntimeException(e);
}
}
}
}
在execute方法中对于对ExecutionExcetion异常可以做一下处理:
引入依赖:
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>21.0</version>
</dependency>
private static void execute(ThreadPoolExecutor executor, Collection<Callable<String>> tasks) {
CompletionService<String> completionService = new ExecutorCompletionService<>(executor);
List<Future<String>> futures = new ArrayList<>(tasks.size());
for (Callable<String> task : tasks) {
futures.add(completionService.submit(task));
}
for (int i = 0; i < futures.size(); i++) {
try {
Future<String> take = completionService.take();
String s = take.get();
System.out.println(s);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new RuntimeException(e);
} catch (ExecutionException e) {
Throwable cause = e.getCause() == null ? e : e.getCause();
Throwables.propagateIfPossible(cause, RuntimeException.class);
throw new RuntimeException(cause);
}
}
}
可以看出异常信息清晰了很多,便于开发人员分析。在上面的代码中通过getCause方法获取了来获取真实的异常。接下来使用了Google Guava提供的Throwable类来进行错误的转播与检查,当异常类型为RunTimeException进行抛出,最后使用Throw new RuntimeException(cause)进行兜底。