1
2
3
4
5
6
7
8
9
10
11
12
13
14
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
39
40
41
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
66 }
67 }, null),
68
69
70 deadlineNanos(getCurrentTimeNanos(), SCHEDULE_QUIET_PERIOD_INTERVAL),
71 -SCHEDULE_QUIET_PERIOD_INTERVAL
72 );
73
74
75
76
77
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 = new FailedFuture<Object>(this, new UnsupportedOperationException());
84
85 private GlobalEventExecutor() {
86 scheduledTaskQueue().add(quietPeriodTask);
87 threadFactory = ThreadExecutorMap.apply(new DefaultThreadFactory(
88 DefaultThreadFactory.toPoolName(getClass()), false, Thread.NORM_PRIORITY, null), this);
89 }
90
91
92
93
94
95
96 Runnable takeTask() {
97 BlockingQueue<Runnable> taskQueue = this.taskQueue;
98 for (;;) {
99 ScheduledFutureTask<?> scheduledTask = peekScheduledTask();
100 if (scheduledTask == null) {
101 Runnable task = null;
102 try {
103 task = taskQueue.take();
104 } catch (InterruptedException e) {
105
106 }
107 return task;
108 } else {
109 long delayNanos = scheduledTask.delayNanos();
110 Runnable task = null;
111 if (delayNanos > 0) {
112 try {
113 task = taskQueue.poll(delayNanos, TimeUnit.NANOSECONDS);
114 } catch (InterruptedException e) {
115
116 return null;
117 }
118 }
119 if (task == null) {
120
121
122
123
124 fetchFromScheduledTaskQueue();
125 task = taskQueue.poll();
126 }
127
128 if (task != null) {
129 return task;
130 }
131 }
132 }
133 }
134
135 private void fetchFromScheduledTaskQueue() {
136 long nanoTime = getCurrentTimeNanos();
137 Runnable scheduledTask = pollScheduledTask(nanoTime);
138 while (scheduledTask != null) {
139 taskQueue.add(scheduledTask);
140 scheduledTask = pollScheduledTask(nanoTime);
141 }
142 }
143
144
145
146
147 public int pendingTasks() {
148 return taskQueue.size();
149 }
150
151
152
153
154
155 private void addTask(Runnable task) {
156 taskQueue.add(ObjectUtil.checkNotNull(task, "task"));
157 }
158
159 @Override
160 public boolean inEventLoop(Thread thread) {
161 return thread == this.thread;
162 }
163
164 @Override
165 public Future<?> shutdownGracefully(long quietPeriod, long timeout, TimeUnit unit) {
166 return terminationFuture();
167 }
168
169 @Override
170 public Future<?> terminationFuture() {
171 return terminationFuture;
172 }
173
174 @Override
175 @Deprecated
176 public void shutdown() {
177 throw new UnsupportedOperationException();
178 }
179
180 @Override
181 public boolean isShuttingDown() {
182 return false;
183 }
184
185 @Override
186 public boolean isShutdown() {
187 return false;
188 }
189
190 @Override
191 public boolean isTerminated() {
192 return false;
193 }
194
195 @Override
196 public boolean awaitTermination(long timeout, TimeUnit unit) {
197 return false;
198 }
199
200
201
202
203
204
205
206
207
208 public boolean awaitInactivity(long timeout, TimeUnit unit) throws InterruptedException {
209 ObjectUtil.checkNotNull(unit, "unit");
210
211 final Thread thread = this.thread;
212 if (thread == null) {
213 throw new IllegalStateException("thread was not started");
214 }
215 thread.join(unit.toMillis(timeout));
216 return !thread.isAlive();
217 }
218
219 @Override
220 public void execute(Runnable task) {
221 execute0(task);
222 }
223
224 private void execute0(@Schedule Runnable task) {
225 addTask(ObjectUtil.checkNotNull(task, "task"));
226 if (!inEventLoop()) {
227 startThread();
228 }
229 }
230
231 private void startThread() {
232 if (started.compareAndSet(false, true)) {
233 final Thread t = threadFactory.newThread(taskRunner);
234
235
236
237
238
239 AccessController.doPrivileged(new PrivilegedAction<Void>() {
240 @Override
241 public Void run() {
242 t.setContextClassLoader(null);
243 return null;
244 }
245 });
246
247
248
249
250 thread = t;
251 t.start();
252 }
253 }
254
255 final class TaskRunner implements Runnable {
256 @Override
257 public void run() {
258 for (;;) {
259 Runnable task = takeTask();
260 if (task != null) {
261 try {
262 runTask(task);
263 } catch (Throwable t) {
264 logger.warn("Unexpected exception from the global event executor: ", t);
265 }
266
267 if (task != quietPeriodTask) {
268 continue;
269 }
270 }
271
272 Queue<ScheduledFutureTask<?>> scheduledTaskQueue = GlobalEventExecutor.this.scheduledTaskQueue;
273
274 if (taskQueue.isEmpty() && (scheduledTaskQueue == null || scheduledTaskQueue.size() == 1)) {
275
276
277
278 boolean stopped = started.compareAndSet(true, false);
279 assert stopped;
280
281
282
283
284 if (taskQueue.isEmpty()) {
285
286
287
288
289 break;
290 }
291
292
293 if (!started.compareAndSet(false, true)) {
294
295
296 break;
297 }
298
299
300
301
302 }
303 }
304 }
305 }
306 }