Added shutdown() for ExecutorService

This commit is contained in:
Bruce Eckel 2016-12-04 12:15:21 -08:00
parent 50228968db
commit 6545d1606b
6 changed files with 16 additions and 18 deletions

View File

@ -3,7 +3,6 @@
// We make no guarantees that this code is fit for any purpose.
// Visit http://OnJava8.com for more book information.
import java.util.concurrent.*;
import onjava.TimedAbort;
class ExceptionThread2 implements Runnable {
@Override
@ -40,21 +39,17 @@ class HandlerThreadFactory implements ThreadFactory {
public class CaptureUncaughtException {
public static void main(String[] args) {
new TimedAbort(4);
ExecutorService exec = Executors.newCachedThreadPool(
new HandlerThreadFactory());
exec.execute(new ExceptionThread2());
exec.shutdown();
}
}
/* Output:
HandlerThreadFactory@14991ad creating new Thread
created Thread[Thread-1,5,main]
eh = MyUncaughtExceptionHandler@d93b30
run() by Thread-1
eh = MyUncaughtExceptionHandler@d93b30
HandlerThreadFactory@14991ad creating new Thread
created Thread[Thread-2,5,main]
eh = MyUncaughtExceptionHandler@1351c58
HandlerThreadFactory@4e25154f creating new Thread
created Thread[Thread-0,5,main]
eh = MyUncaughtExceptionHandler@70dea4e
run() by Thread-0
eh = MyUncaughtExceptionHandler@70dea4e
caught java.lang.RuntimeException
TimedAbort 4
*/

View File

@ -14,5 +14,6 @@ public class ExceptionThread implements Runnable {
public static void main(String[] args) {
ExecutorService es = Executors.newCachedThreadPool();
es.execute(new ExceptionThread());
es.shutdown();
}
}

View File

@ -8,13 +8,15 @@ import java.util.concurrent.*;
public class NaiveExceptionHandling {
public static void main(String[] args) {
ExecutorService es =
Executors.newCachedThreadPool();
try {
ExecutorService exec =
Executors.newCachedThreadPool();
exec.execute(new ExceptionThread());
es.execute(new ExceptionThread());
} catch(RuntimeException ue) {
// This statement will NOT execute!
System.out.println("Exception was handled!");
} finally {
es.shutdown();
}
}
}

View File

@ -3,18 +3,16 @@
// We make no guarantees that this code is fit for any purpose.
// Visit http://OnJava8.com for more book information.
import java.util.concurrent.*;
import onjava.TimedAbort;
public class SettingDefaultHandler {
public static void main(String[] args) {
new TimedAbort(4);
Thread.setDefaultUncaughtExceptionHandler(
new MyUncaughtExceptionHandler());
ExecutorService es = Executors.newCachedThreadPool();
es.execute(new ExceptionThread());
es.shutdown();
}
}
/* Output:
caught java.lang.RuntimeException
TimedAbort 4
*/

View File

@ -12,6 +12,6 @@ public class SwallowedException {
exec.submit(() -> {
throw new RuntimeException();
});
exec.shutdownNow();
exec.shutdown();
}
}

View File

@ -29,6 +29,8 @@ public class ThreadSize {
System.out.println(
e.getClass().getSimpleName() + ": " + count);
System.exit(0);
} finally {
exec.shutdown();
}
}
}