1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package org.jboss.netty.util.internal;
17
18 import java.util.concurrent.Executor;
19 import java.util.concurrent.ExecutorService;
20 import java.util.concurrent.TimeUnit;
21
22
23
24
25
26
27
28 public final class ExecutorUtil {
29
30
31
32
33 public static void shutdownNow(Executor executor) {
34 if (executor instanceof ExecutorService) {
35 ExecutorService es = (ExecutorService) executor;
36 try {
37 es.shutdownNow();
38 } catch (SecurityException ex) {
39
40 try {
41 es.shutdown();
42 } catch (SecurityException ex2) {
43
44
45 } catch (NullPointerException ex2) {
46
47 }
48 } catch (NullPointerException ex) {
49
50 }
51 }
52 }
53
54
55
56
57
58
59
60 public static boolean isShutdown(Executor executor) {
61 if (executor instanceof ExecutorService) {
62 if (((ExecutorService) executor).isShutdown()) {
63 return true;
64 }
65 }
66 return false;
67 }
68
69
70
71
72 public static void terminate(Executor... executors) {
73 terminate(DeadLockProofWorker.PARENT, executors);
74 }
75
76
77
78 public static void terminate(ThreadLocal<Executor> deadLockChecker, Executor... executors) {
79
80 if (executors == null) {
81 throw new NullPointerException("executors");
82 }
83
84 Executor[] executorsCopy = new Executor[executors.length];
85 for (int i = 0; i < executors.length; i ++) {
86 if (executors[i] == null) {
87 throw new NullPointerException("executors[" + i + ']');
88 }
89 executorsCopy[i] = executors[i];
90 }
91
92
93 final Executor currentParent = deadLockChecker.get();
94 if (currentParent != null) {
95 for (Executor e: executorsCopy) {
96 if (e == currentParent) {
97 throw new IllegalStateException(
98 "An Executor cannot be shut down from the thread " +
99 "acquired from itself. Please make sure you are " +
100 "not calling releaseExternalResources() from an " +
101 "I/O worker thread.");
102 }
103 }
104 }
105
106
107 boolean interrupted = false;
108 for (Executor e: executorsCopy) {
109 if (!(e instanceof ExecutorService)) {
110 continue;
111 }
112
113 ExecutorService es = (ExecutorService) e;
114 for (;;) {
115 shutdownNow(es);
116
117 try {
118 if (es.awaitTermination(100, TimeUnit.MILLISECONDS)) {
119 break;
120 }
121 } catch (InterruptedException ex) {
122 interrupted = true;
123 }
124 }
125 }
126
127 if (interrupted) {
128 Thread.currentThread().interrupt();
129 }
130 }
131
132 private ExecutorUtil() {
133 }
134 }