Java Reference
In-Depth Information
Exception in thread "pool-1-thread-1" java.lang.RuntimeException: Throwing exception from task
execution...
at com.jdojo.threads.BadRunnableTask.lambda$main$0(BadRunnableTask.java:10)
at com.jdojo.threads.BadRunnableTask$$Lambda$1/2536472.run(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
If you are submitting a task using the submit() method of the ExecutorService , the executor framework handles
the exception and indicates that to you when you use the get() method to get the result of the task execution. The
get() method on the Future object throws a ExecutionException , wrapping the actual exception as its cause.
Listing 6-54 illustrates this kind of example. You can use the get() method of the Future object even if you submit
a Runnable task. On successful execution of the task, the get() method will return a Void object. If an uncaught
exception is thrown during the task execution, it throws an ExecutionException .
Listing 6-54. Future's get() Method Throws ExecutionException, Wrapping the Actual Exception Thrown in Task
Execution as Its Cause
// BadCallableTask.java
package com.jdojo.threads;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Callable;
import java.util.concurrent.Future;
import java.util.concurrent.ExecutionException;
public class BadCallableTask {
public static void main(String[] args) {
Callable<Object> badTask = () -> {
throw new RuntimeException("Throwing exception from task execution...");
};
// CReate an executor service
ExecutorService exec = Executors.newSingleThreadExecutor();
// Submit a task
Future submittedTask = exec.submit(badTask);
try {
// The get method should throw ExecutionException
Object result = submittedTask.get();
}
catch(ExecutionException e) {
System.out.println("Execution exception has occurred: " +
e.getMessage());
System.out.println("Execution exception cause is: " +
e.getCause().getMessage());
}
Search WWH ::




Custom Search