View Javadoc
1   /*
2    * Copyright 2014 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  
17  package io.netty.util;
18  
19  import io.netty.util.concurrent.DefaultThreadFactory;
20  import io.netty.util.internal.StringUtil;
21  import io.netty.util.internal.SystemPropertyUtil;
22  import io.netty.util.internal.logging.InternalLogger;
23  import io.netty.util.internal.logging.InternalLoggerFactory;
24  
25  import java.util.ArrayList;
26  import java.util.List;
27  import java.util.Queue;
28  import java.util.concurrent.ConcurrentLinkedQueue;
29  import java.util.concurrent.ThreadFactory;
30  import java.util.concurrent.TimeUnit;
31  import java.util.concurrent.atomic.AtomicBoolean;
32  
33  /**
34   * Checks if a thread is alive periodically and runs a task when a thread dies.
35   * <p>
36   * This thread starts a daemon thread to check the state of the threads being watched and to invoke their
37   * associated {@link Runnable}s.  When there is no thread to watch (i.e. all threads are dead), the daemon thread
38   * will terminate itself, and a new daemon thread will be started again when a new watch is added.
39   * </p>
40   */
41  public final class ThreadDeathWatcher {
42  
43      private static final InternalLogger logger = InternalLoggerFactory.getInstance(ThreadDeathWatcher.class);
44      // visible for testing
45      static final ThreadFactory threadFactory;
46  
47      // Use a MPMC queue as we may end up checking isEmpty() from multiple threads which may not be allowed to do
48      // concurrently depending on the implementation of it in a MPSC queue.
49      private static final Queue<Entry> pendingEntries = new ConcurrentLinkedQueue<Entry>();
50      private static final Watcher watcher = new Watcher();
51      private static final AtomicBoolean started = new AtomicBoolean();
52      private static volatile Thread watcherThread;
53  
54      static {
55          String poolName = "threadDeathWatcher";
56          String serviceThreadPrefix = SystemPropertyUtil.get("io.netty.serviceThreadPrefix");
57          if (!StringUtil.isNullOrEmpty(serviceThreadPrefix)) {
58              poolName = serviceThreadPrefix + poolName;
59          }
60          // because the ThreadDeathWatcher is a singleton, tasks submitted to it can come from arbitrary threads and
61          // this can trigger the creation of a thread from arbitrary thread groups; for this reason, the thread factory
62          // must not be sticky about its thread group
63          threadFactory = new DefaultThreadFactory(poolName, true, Thread.MIN_PRIORITY, null);
64      }
65  
66      /**
67       * Schedules the specified {@code task} to run when the specified {@code thread} dies.
68       *
69       * @param thread the {@link Thread} to watch
70       * @param task the {@link Runnable} to run when the {@code thread} dies
71       *
72       * @throws IllegalArgumentException if the specified {@code thread} is not alive
73       */
74      public static void watch(Thread thread, Runnable task) {
75          if (thread == null) {
76              throw new NullPointerException("thread");
77          }
78          if (task == null) {
79              throw new NullPointerException("task");
80          }
81          if (!thread.isAlive()) {
82              throw new IllegalArgumentException("thread must be alive.");
83          }
84  
85          schedule(thread, task, true);
86      }
87  
88      /**
89       * Cancels the task scheduled via {@link #watch(Thread, Runnable)}.
90       */
91      public static void unwatch(Thread thread, Runnable task) {
92          if (thread == null) {
93              throw new NullPointerException("thread");
94          }
95          if (task == null) {
96              throw new NullPointerException("task");
97          }
98  
99          schedule(thread, task, false);
100     }
101 
102     private static void schedule(Thread thread, Runnable task, boolean isWatch) {
103         pendingEntries.add(new Entry(thread, task, isWatch));
104 
105         if (started.compareAndSet(false, true)) {
106             Thread watcherThread = threadFactory.newThread(watcher);
107             watcherThread.start();
108             ThreadDeathWatcher.watcherThread = watcherThread;
109         }
110     }
111 
112     /**
113      * Waits until the thread of this watcher has no threads to watch and terminates itself.
114      * Because a new watcher thread will be started again on {@link #watch(Thread, Runnable)},
115      * this operation is only useful when you want to ensure that the watcher thread is terminated
116      * <strong>after</strong> your application is shut down and there's no chance of calling
117      * {@link #watch(Thread, Runnable)} afterwards.
118      *
119      * @return {@code true} if and only if the watcher thread has been terminated
120      */
121     public static boolean awaitInactivity(long timeout, TimeUnit unit) throws InterruptedException {
122         if (unit == null) {
123             throw new NullPointerException("unit");
124         }
125 
126         Thread watcherThread = ThreadDeathWatcher.watcherThread;
127         if (watcherThread != null) {
128             watcherThread.join(unit.toMillis(timeout));
129             return !watcherThread.isAlive();
130         } else {
131             return true;
132         }
133     }
134 
135     private ThreadDeathWatcher() { }
136 
137     private static final class Watcher implements Runnable {
138 
139         private final List<Entry> watchees = new ArrayList<Entry>();
140 
141         @Override
142         public void run() {
143             for (;;) {
144                 fetchWatchees();
145                 notifyWatchees();
146 
147                 // Try once again just in case notifyWatchees() triggered watch() or unwatch().
148                 fetchWatchees();
149                 notifyWatchees();
150 
151                 try {
152                     Thread.sleep(1000);
153                 } catch (InterruptedException ignore) {
154                     // Ignore the interrupt; do not terminate until all tasks are run.
155                 }
156 
157                 if (watchees.isEmpty() && pendingEntries.isEmpty()) {
158 
159                     // Mark the current worker thread as stopped.
160                     // The following CAS must always success and must be uncontended,
161                     // because only one watcher thread should be running at the same time.
162                     boolean stopped = started.compareAndSet(true, false);
163                     assert stopped;
164 
165                     // Check if there are pending entries added by watch() while we do CAS above.
166                     if (pendingEntries.isEmpty()) {
167                         // A) watch() was not invoked and thus there's nothing to handle
168                         //    -> safe to terminate because there's nothing left to do
169                         // B) a new watcher thread started and handled them all
170                         //    -> safe to terminate the new watcher thread will take care the rest
171                         break;
172                     }
173 
174                     // There are pending entries again, added by watch()
175                     if (!started.compareAndSet(false, true)) {
176                         // watch() started a new watcher thread and set 'started' to true.
177                         // -> terminate this thread so that the new watcher reads from pendingEntries exclusively.
178                         break;
179                     }
180 
181                     // watch() added an entry, but this worker was faster to set 'started' to true.
182                     // i.e. a new watcher thread was not started
183                     // -> keep this thread alive to handle the newly added entries.
184                 }
185             }
186         }
187 
188         private void fetchWatchees() {
189             for (;;) {
190                 Entry e = pendingEntries.poll();
191                 if (e == null) {
192                     break;
193                 }
194 
195                 if (e.isWatch) {
196                     watchees.add(e);
197                 } else {
198                     watchees.remove(e);
199                 }
200             }
201         }
202 
203         private void notifyWatchees() {
204             List<Entry> watchees = this.watchees;
205             for (int i = 0; i < watchees.size();) {
206                 Entry e = watchees.get(i);
207                 if (!e.thread.isAlive()) {
208                     watchees.remove(i);
209                     try {
210                         e.task.run();
211                     } catch (Throwable t) {
212                         logger.warn("Thread death watcher task raised an exception:", t);
213                     }
214                 } else {
215                     i ++;
216                 }
217             }
218         }
219     }
220 
221     private static final class Entry {
222         final Thread thread;
223         final Runnable task;
224         final boolean isWatch;
225 
226         Entry(Thread thread, Runnable task, boolean isWatch) {
227             this.thread = thread;
228             this.task = task;
229             this.isWatch = isWatch;
230         }
231 
232         @Override
233         public int hashCode() {
234             return thread.hashCode() ^ task.hashCode();
235         }
236 
237         @Override
238         public boolean equals(Object obj) {
239             if (obj == this) {
240                 return true;
241             }
242 
243             if (!(obj instanceof Entry)) {
244                 return false;
245             }
246 
247             Entry that = (Entry) obj;
248             return thread == that.thread && task == that.task;
249         }
250     }
251 }