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
29
30
31
32 public class ExecutorUtil {
33
34
35
36
37
38
39
40 public static boolean isShutdown(Executor executor) {
41 if (executor instanceof ExecutorService) {
42 if (((ExecutorService) executor).isShutdown()) {
43 return true;
44 }
45 }
46 return false;
47 }
48
49
50
51
52 public static void terminate(Executor... executors) {
53
54 if (executors == null) {
55 throw new NullPointerException("executors");
56 }
57
58 Executor[] executorsCopy = new Executor[executors.length];
59 for (int i = 0; i < executors.length; i ++) {
60 if (executors[i] == null) {
61 throw new NullPointerException("executors[" + i + "]");
62 }
63 executorsCopy[i] = executors[i];
64 }
65
66
67 final Executor currentParent = DeadLockProofWorker.PARENT.get();
68 if (currentParent != null) {
69 for (Executor e: executorsCopy) {
70 if (e == currentParent) {
71 throw new IllegalStateException(
72 "An Executor cannot be shut down from the thread " +
73 "acquired from itself. Please make sure you are " +
74 "not calling releaseExternalResources() from an " +
75 "I/O worker thread.");
76 }
77 }
78 }
79
80
81 boolean interrupted = false;
82 for (Executor e: executorsCopy) {
83 if (!(e instanceof ExecutorService)) {
84 continue;
85 }
86
87 ExecutorService es = (ExecutorService) e;
88 for (;;) {
89 try {
90 es.shutdownNow();
91 } catch (SecurityException ex) {
92
93 try {
94 es.shutdown();
95 } catch (SecurityException ex2) {
96
97
98 break;
99 } catch (NullPointerException ex2) {
100
101 }
102 } catch (NullPointerException ex) {
103
104 }
105
106 try {
107 if (es.awaitTermination(100, TimeUnit.MILLISECONDS)) {
108 break;
109 }
110 } catch (InterruptedException ex) {
111 interrupted = true;
112 }
113 }
114 }
115
116 if (interrupted) {
117 Thread.currentThread().interrupt();
118 }
119 }
120
121 private ExecutorUtil() {
122 super();
123 }
124 }