View Javadoc
1   /*
2    * Copyright 2012 The Netty Project
3    *
4    * The Netty Project licenses this file to you under the Apache License,
5    * version 2.0 (the "License"); you may not use this file except in compliance
6    * with the License. You may obtain a copy of the License at:
7    *
8    *   http://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12   * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13   * License for the specific language governing permissions and limitations
14   * under the License.
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   * Shuts down a list of {@link Executor}s.  {@link #terminate(Executor...)} will
24   * shut down all specified {@link ExecutorService}s immediately and wait for
25   * their termination.  An {@link Executor} which is not an {@link ExecutorService}
26   * will be ignored silently.
27   */
28  public final class ExecutorUtil {
29  
30      /**
31       * Try to call {@link ExecutorService#shutdownNow()}
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                  // Running in a restricted environment - fall back.
40                  try {
41                      es.shutdown();
42                  } catch (SecurityException ex2) {
43                      // Running in a more restricted environment.
44                      // Can't shut down this executor - skip to the next.
45                  } catch (NullPointerException ex2) {
46                      // Some JDK throws NPE here, but shouldn't.
47                  }
48              } catch (NullPointerException ex) {
49                  // Some JDK throws NPE here, but shouldn't.
50              }
51          }
52      }
53  
54      /**
55       * Returns {@code true} if and only if the specified {@code executor}
56       * is an {@link ExecutorService} and is shut down.  Please note that this
57       * method returns {@code false} if the specified {@code executor} is not an
58       * {@link ExecutorService}.
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       * Shuts down the specified executors.
71       */
72      public static void terminate(Executor... executors) {
73          terminate(DeadLockProofWorker.PARENT, executors);
74      }
75      /**
76       * Shuts down the specified executors using the given {@link ThreadLocal} to check if there is a deadlock
77       */
78      public static void terminate(ThreadLocal<Executor> deadLockChecker, Executor... executors) {
79          // Check nulls.
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          // Check dead lock.
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         // Shut down all executors.
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 }