Java Reference
In-Depth Information
// Let the current thread sleep for 60 seconds and shut down the executor that
// will cancel the task #2 because it is scheduled to run after every 10 seconds
try {
TimeUnit.SECONDS.sleep(60);
}
catch(InterruptedException e) {
e.printStackTrace();
}
// Shut down the executor
sexec.shutdown();
}
}
(You may get a different output.)
Task #1 ran at 2014-04-23T11:22:14.089
Task #2 ran at 2014-04-23T11:22:17.032
Task #2 ran at 2014-04-23T11:22:27.033
Task #2 ran at 2014-04-23T11:22:37.033
Task #2 ran at 2014-04-23T11:22:47.034
Task #2 ran at 2014-04-23T11:22:57.034
Task #2 ran at 2014-04-23T11:23:07.035
Handling Uncaught Exceptions in a Task Execution
What happens when an uncaught exception occurs during a task execution? The executor framework handles
occurrences of any uncaught exception during task execution nicely for you. If you execute a Runnable task using
the execute() method of the Executor object, any uncaught runtime exceptions will halt the task execution, and the
exception stack trace will be printed on the console, as shown in the output of Listing 6-53.
Listing 6-53. Printing the Runtime Stack Trace from the execute() Method of the Executor
// BadRunnableTask.java
package com.jdojo.threads;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class BadRunnableTask {
public static void main(String[] args) {
Runnable badTask = () -> {
throw new RuntimeException("Throwing exception from task execution...");
};
ExecutorService exec = Executors.newSingleThreadExecutor();
exec.execute(badTask);
exec.shutdown();
}
}
 
Search WWH ::




Custom Search