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