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