Created
September 14, 2014 05:20
-
-
Save kavinyao/b255109e75bf910d7a94 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.concurrent.ExecutorService; | |
import java.util.concurrent.Executors; | |
import java.util.concurrent.TimeUnit; | |
/** | |
* Demo of exception handling in ExecutorService. | |
*/ | |
public class ExecutorServiceExceptionDemo { | |
/** | |
* A simple job which doesn't handle RuntimeException. | |
*/ | |
private static class ExceptionalNumberPrintingJob implements Runnable { | |
private final int number; | |
public ExceptionalNumberPrintingJob(int num) { | |
this.number = num; | |
} | |
@Override | |
public void run() { | |
String threadName = Thread.currentThread().getName(); | |
// randomly trigger a RTE (ArithmeticException in this case) | |
if (Math.random() < 0.5) { | |
double q = 1 / 0; | |
} | |
System.out.println(String.format("Thread %s is printing %d.", threadName, number)); | |
} | |
} | |
/** | |
* Stop new job from being submitted and wait termination. | |
* Taken from official documentation: | |
* http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ExecutorService.html | |
* @param pool the thread pool | |
*/ | |
private static void shutdownAndAwaitTermination(ExecutorService pool) { | |
pool.shutdown(); // Disable new tasks from being submitted | |
try { | |
// Wait a while for existing tasks to terminate | |
if (!pool.awaitTermination(60, TimeUnit.SECONDS)) { | |
pool.shutdownNow(); // Cancel currently executing tasks | |
// Wait a while for tasks to respond to being cancelled | |
if (!pool.awaitTermination(60, TimeUnit.SECONDS)) | |
System.err.println("Pool did not terminate"); | |
} | |
} catch (InterruptedException ie) { | |
// (Re-)Cancel if current thread also interrupted | |
pool.shutdownNow(); | |
// Preserve interrupt status | |
Thread.currentThread().interrupt(); | |
} | |
} | |
public static void main(String[] args) { | |
ExecutorService threadPool = Executors.newFixedThreadPool(2); | |
for (int i = 0; i < 10; ++i) { | |
threadPool.submit(new ExceptionalNumberPrintingJob(i)); | |
} | |
shutdownAndAwaitTermination(threadPool); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment