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;
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
96
97
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
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
119 return null;
120 }
121 }
122 if (task == null) {
123
124
125
126
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
149
150 public int pendingTasks() {
151 return taskQueue.size();
152 }
153
154
155
156
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
205
206
207
208
209
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
244 setContextClassLoader(callingThread, null);
245 try {
246 final Thread t = threadFactory.newThread(taskRunner);
247
248
249
250
251
252 setContextClassLoader(t, null);
253
254
255
256
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
294 if (taskQueue.isEmpty() && (scheduledTaskQueue == null || scheduledTaskQueue.size() == 1)) {
295
296
297
298 boolean stopped = started.compareAndSet(true, false);
299 assert stopped;
300
301
302
303
304 if (taskQueue.isEmpty()) {
305
306
307
308
309 break;
310 }
311
312
313 if (!started.compareAndSet(false, true)) {
314
315
316 break;
317 }
318
319
320
321
322 }
323 }
324 }
325 }
326 }