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    *   https://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 io.netty.util.concurrent;
17  
18  import io.netty.util.internal.ObjectUtil;
19  import io.netty.util.internal.SystemPropertyUtil;
20  import io.netty.util.internal.ThreadExecutorMap;
21  import io.netty.util.internal.logging.InternalLogger;
22  import io.netty.util.internal.logging.InternalLoggerFactory;
23  
24  import org.jetbrains.annotations.Async.Schedule;
25  
26  import java.security.AccessController;
27  import java.security.PrivilegedAction;
28  import java.util.Queue;
29  import java.util.concurrent.BlockingQueue;
30  import java.util.concurrent.Executors;
31  import java.util.concurrent.LinkedBlockingQueue;
32  import java.util.concurrent.RejectedExecutionException;
33  import java.util.concurrent.ThreadFactory;
34  import java.util.concurrent.TimeUnit;
35  import java.util.concurrent.atomic.AtomicBoolean;
36  
37  /**
38   * Single-thread singleton {@link EventExecutor}.  It starts the thread automatically and stops it when there is no
39   * task pending in the task queue for {@code io.netty.globalEventExecutor.quietPeriodSeconds} second
40   * (default is 1 second).  Please note it is not scalable to schedule large number of tasks to this executor;
41   * use a dedicated executor.
42   */
43  public final class GlobalEventExecutor extends AbstractScheduledEventExecutor implements OrderedEventExecutor {
44      private static final InternalLogger logger = InternalLoggerFactory.getInstance(GlobalEventExecutor.class);
45  
46      private static final long SCHEDULE_QUIET_PERIOD_INTERVAL;
47  
48      static {
49          int quietPeriod = SystemPropertyUtil.getInt("io.netty.globalEventExecutor.quietPeriodSeconds", 1);
50          if (quietPeriod <= 0) {
51              quietPeriod = 1;
52          }
53          logger.debug("-Dio.netty.globalEventExecutor.quietPeriodSeconds: {}", quietPeriod);
54  
55          SCHEDULE_QUIET_PERIOD_INTERVAL = TimeUnit.SECONDS.toNanos(quietPeriod);
56      }
57  
58      public static final GlobalEventExecutor INSTANCE = new GlobalEventExecutor();
59  
60      final BlockingQueue<Runnable> taskQueue = new LinkedBlockingQueue<Runnable>();
61      final ScheduledFutureTask<Void> quietPeriodTask = new ScheduledFutureTask<Void>(
62              this, Executors.<Void>callable(new Runnable() {
63          @Override
64          public void run() {
65              // NOOP
66          }
67      }, null),
68              // note: the getCurrentTimeNanos() call here only works because this is a final class, otherwise the method
69              // could be overridden leading to unsafe initialization here!
70              deadlineNanos(getCurrentTimeNanos(), SCHEDULE_QUIET_PERIOD_INTERVAL),
71              -SCHEDULE_QUIET_PERIOD_INTERVAL
72      );
73  
74      // because the GlobalEventExecutor is a singleton, tasks submitted to it can come from arbitrary threads and this
75      // can trigger the creation of a thread from arbitrary thread groups; for this reason, the thread factory must not
76      // be sticky about its thread group
77      // visible for testing
78      final ThreadFactory threadFactory;
79      private final TaskRunner taskRunner = new TaskRunner();
80      private final AtomicBoolean started = new AtomicBoolean();
81      volatile Thread thread;
82  
83      private final Future<?> terminationFuture;
84  
85      private GlobalEventExecutor() {
86          scheduleFromEventLoop(quietPeriodTask);
87          threadFactory = ThreadExecutorMap.apply(new DefaultThreadFactory(
88                  DefaultThreadFactory.toPoolName(getClass()), false, Thread.NORM_PRIORITY, null), this);
89  
90          terminationFuture = new FailedFuture<Object>(this,
91                  StacklessUnsupportedOperationException.newInstance(GlobalEventExecutor.class, "terminationFuture"));
92      }
93  
94      /**
95       * Take the next {@link Runnable} from the task queue and so will block if no task is currently present.
96       *
97       * @return {@code null} if the executor thread has been interrupted or waken up.
98       */
99      Runnable takeTask() {
100         BlockingQueue<Runnable> taskQueue = this.taskQueue;
101         for (;;) {
102             ScheduledFutureTask<?> scheduledTask = peekScheduledTask();
103             if (scheduledTask == null) {
104                 Runnable task = null;
105                 try {
106                     task = taskQueue.take();
107                 } catch (InterruptedException e) {
108                     // Ignore
109                 }
110                 return task;
111             } else {
112                 long delayNanos = scheduledTask.delayNanos();
113                 Runnable task = null;
114                 if (delayNanos > 0) {
115                     try {
116                         task = taskQueue.poll(delayNanos, TimeUnit.NANOSECONDS);
117                     } catch (InterruptedException e) {
118                         // Waken up.
119                         return null;
120                     }
121                 }
122                 if (task == null) {
123                     // We need to fetch the scheduled tasks now as otherwise there may be a chance that
124                     // scheduled tasks are never executed if there is always one task in the taskQueue.
125                     // This is for example true for the read task of OIO Transport
126                     // See https://github.com/netty/netty/issues/1614
127                     fetchFromScheduledTaskQueue();
128                     task = taskQueue.poll();
129                 }
130 
131                 if (task != null) {
132                     return task;
133                 }
134             }
135         }
136     }
137 
138     private void fetchFromScheduledTaskQueue() {
139         long nanoTime = getCurrentTimeNanos();
140         Runnable scheduledTask = pollScheduledTask(nanoTime);
141         while (scheduledTask != null) {
142             taskQueue.add(scheduledTask);
143             scheduledTask = pollScheduledTask(nanoTime);
144         }
145     }
146 
147     /**
148      * Return the number of tasks that are pending for processing.
149      */
150     public int pendingTasks() {
151         return taskQueue.size();
152     }
153 
154     /**
155      * Add a task to the task queue, or throws a {@link RejectedExecutionException} if this instance was shutdown
156      * before.
157      */
158     private void addTask(Runnable task) {
159         taskQueue.add(ObjectUtil.checkNotNull(task, "task"));
160     }
161 
162     @Override
163     public boolean inEventLoop(Thread thread) {
164         return thread == this.thread;
165     }
166 
167     @Override
168     public Future<?> shutdownGracefully(long quietPeriod, long timeout, TimeUnit unit) {
169         return terminationFuture();
170     }
171 
172     @Override
173     public Future<?> terminationFuture() {
174         return terminationFuture;
175     }
176 
177     @Override
178     @Deprecated
179     public void shutdown() {
180         throw new UnsupportedOperationException();
181     }
182 
183     @Override
184     public boolean isShuttingDown() {
185         return false;
186     }
187 
188     @Override
189     public boolean isShutdown() {
190         return false;
191     }
192 
193     @Override
194     public boolean isTerminated() {
195         return false;
196     }
197 
198     @Override
199     public boolean awaitTermination(long timeout, TimeUnit unit) {
200         return false;
201     }
202 
203     /**
204      * Waits until the worker thread of this executor has no tasks left in its task queue and terminates itself.
205      * Because a new worker thread will be started again when a new task is submitted, this operation is only useful
206      * when you want to ensure that the worker thread is terminated <strong>after</strong> your application is shut
207      * down and there's no chance of submitting a new task afterwards.
208      *
209      * @return {@code true} if and only if the worker thread has been terminated
210      */
211     public boolean awaitInactivity(long timeout, TimeUnit unit) throws InterruptedException {
212         ObjectUtil.checkNotNull(unit, "unit");
213 
214         final Thread thread = this.thread;
215         if (thread == null) {
216             throw new IllegalStateException("thread was not started");
217         }
218         thread.join(unit.toMillis(timeout));
219         return !thread.isAlive();
220     }
221 
222     @Override
223     public void execute(Runnable task) {
224         execute0(task);
225     }
226 
227     private void execute0(@Schedule Runnable task) {
228         addTask(ObjectUtil.checkNotNull(task, "task"));
229         if (!inEventLoop()) {
230             startThread();
231         }
232     }
233 
234     private void startThread() {
235         if (started.compareAndSet(false, true)) {
236             final Thread callingThread = Thread.currentThread();
237             ClassLoader parentCCL = AccessController.doPrivileged(new PrivilegedAction<ClassLoader>() {
238                 @Override
239                 public ClassLoader run() {
240                     return callingThread.getContextClassLoader();
241                 }
242             });
243             // Avoid calling classloader leaking through Thread.inheritedAccessControlContext.
244             setContextClassLoader(callingThread, null);
245             try {
246                 final Thread t = threadFactory.newThread(taskRunner);
247                 // Set to null to ensure we not create classloader leaks by holds a strong reference to the inherited
248                 // classloader.
249                 // See:
250                 // - https://github.com/netty/netty/issues/7290
251                 // - https://bugs.openjdk.java.net/browse/JDK-7008595
252                 setContextClassLoader(t, null);
253 
254                 // Set the thread before starting it as otherwise inEventLoop() may return false and so produce
255                 // an assert error.
256                 // See https://github.com/netty/netty/issues/4357
257                 thread = t;
258                 t.start();
259             } finally {
260                 setContextClassLoader(callingThread, parentCCL);
261             }
262         }
263     }
264 
265     private static void setContextClassLoader(final Thread t, final ClassLoader cl) {
266         AccessController.doPrivileged(new PrivilegedAction<Void>() {
267             @Override
268             public Void run() {
269                 t.setContextClassLoader(cl);
270                 return null;
271             }
272         });
273     }
274 
275     final class TaskRunner implements Runnable {
276         @Override
277         public void run() {
278             for (;;) {
279                 Runnable task = takeTask();
280                 if (task != null) {
281                     try {
282                         runTask(task);
283                     } catch (Throwable t) {
284                         logger.warn("Unexpected exception from the global event executor: ", t);
285                     }
286 
287                     if (task != quietPeriodTask) {
288                         continue;
289                     }
290                 }
291 
292                 Queue<ScheduledFutureTask<?>> scheduledTaskQueue = GlobalEventExecutor.this.scheduledTaskQueue;
293                 // Terminate if there is no task in the queue (except the noop task).
294                 if (taskQueue.isEmpty() && (scheduledTaskQueue == null || scheduledTaskQueue.size() == 1)) {
295                     // Mark the current thread as stopped.
296                     // The following CAS must always success and must be uncontended,
297                     // because only one thread should be running at the same time.
298                     boolean stopped = started.compareAndSet(true, false);
299                     assert stopped;
300 
301                     // Check if there are pending entries added by execute() or schedule*() while we do CAS above.
302                     // Do not check scheduledTaskQueue because it is not thread-safe and can only be mutated from a
303                     // TaskRunner actively running tasks.
304                     if (taskQueue.isEmpty()) {
305                         // A) No new task was added and thus there's nothing to handle
306                         //    -> safe to terminate because there's nothing left to do
307                         // B) A new thread started and handled all the new tasks.
308                         //    -> safe to terminate the new thread will take care the rest
309                         break;
310                     }
311 
312                     // There are pending tasks added again.
313                     if (!started.compareAndSet(false, true)) {
314                         // startThread() started a new thread and set 'started' to true.
315                         // -> terminate this thread so that the new thread reads from taskQueue exclusively.
316                         break;
317                     }
318 
319                     // New tasks were added, but this worker was faster to set 'started' to true.
320                     // i.e. a new worker thread was not started by startThread().
321                     // -> keep this thread alive to handle the newly added entries.
322                 }
323             }
324         }
325     }
326 }