View Javadoc
1   /*
2    * Copyright 2024 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.channel;
17  
18  import io.netty.util.concurrent.Future;
19  import io.netty.util.concurrent.Promise;
20  import io.netty.util.concurrent.RejectedExecutionHandler;
21  import io.netty.util.concurrent.SingleThreadEventExecutor;
22  import io.netty.util.internal.ObjectUtil;
23  import io.netty.util.internal.PlatformDependent;
24  import io.netty.util.internal.SystemPropertyUtil;
25  
26  import java.util.Queue;
27  import java.util.concurrent.Executor;
28  import java.util.concurrent.RejectedExecutionException;
29  import java.util.concurrent.ThreadFactory;
30  import java.util.concurrent.TimeUnit;
31  import java.util.concurrent.atomic.AtomicInteger;
32  
33  /**
34   * {@link IoEventLoop} implementation that execute all its submitted tasks in a single thread using the provided
35   * {@link IoHandler}.
36   */
37  public class SingleThreadIoEventLoop extends SingleThreadEventLoop implements IoEventLoop {
38  
39      // TODO: Is this a sensible default ?
40      private static final long DEFAULT_MAX_TASK_PROCESSING_QUANTUM_NS = TimeUnit.MILLISECONDS.toNanos(Math.max(100,
41              SystemPropertyUtil.getInt("io.netty.eventLoop.maxTaskProcessingQuantumMs", 1000)));
42  
43      // 100 preserves the pre-existing behaviour of always using maxTaskProcessingQuantumNs as the task budget.
44      static final int DEFAULT_IO_RATIO = Math.max(1, Math.min(100,
45          SystemPropertyUtil.getInt("io.netty.eventLoop.ioRatio", 100)));
46  
47      private final long maxTaskProcessingQuantumNs;
48      private volatile int ioRatio = DEFAULT_IO_RATIO;
49      private long activeIoTimeNanos = -1;
50      private final IoHandlerContext context = new IoHandlerContext() {
51          @Override
52          public boolean canBlock() {
53              assert inEventLoop();
54              return !hasTasks() && !hasScheduledTasks();
55          }
56  
57          @Override
58          public long delayNanos(long currentTimeNanos) {
59              assert inEventLoop();
60              return SingleThreadIoEventLoop.this.delayNanos(currentTimeNanos);
61          }
62  
63          @Override
64          public long deadlineNanos() {
65              assert inEventLoop();
66              return SingleThreadIoEventLoop.this.deadlineNanos();
67          }
68  
69          @Override
70          public void reportActiveIoTime(long activeNanos) {
71              if (activeNanos >= 0) {
72                  activeIoTimeNanos = activeNanos;
73              }
74              SingleThreadIoEventLoop.this.reportActiveIoTime(activeNanos);
75          }
76  
77          @Override
78          public boolean shouldReportActiveIoTime() {
79              return isSuspensionSupported() || ioRatio != 100;
80          }
81      };
82  
83      private final IoHandler ioHandler;
84  
85      private final AtomicInteger numRegistrations = new AtomicInteger();
86  
87      /**
88       *  Creates a new instance
89       *
90       * @param parent            the parent that holds this {@link IoEventLoop}.
91       * @param threadFactory     the {@link ThreadFactory} that is used to create the underlying {@link Thread}.
92       * @param ioHandlerFactory  the {@link IoHandlerFactory} that should be used to obtain {@link IoHandler} to
93       *                          handle IO.
94       */
95      public SingleThreadIoEventLoop(IoEventLoopGroup parent, ThreadFactory threadFactory,
96                                     IoHandlerFactory ioHandlerFactory) {
97          super(parent, threadFactory, false,
98                  ObjectUtil.checkNotNull(ioHandlerFactory, "ioHandlerFactory").isChangingThreadSupported());
99          this.maxTaskProcessingQuantumNs = DEFAULT_MAX_TASK_PROCESSING_QUANTUM_NS;
100         this.ioHandler = ioHandlerFactory.newHandler(this);
101     }
102 
103     /**
104      *  Creates a new instance
105      *
106      * @param parent            the parent that holds this {@link IoEventLoop}.
107      * @param executor          the {@link Executor} that is used for dispatching the work.
108      * @param ioHandlerFactory  the {@link IoHandlerFactory} that should be used to obtain {@link IoHandler} to
109      *                          handle IO.
110      */
111     public SingleThreadIoEventLoop(IoEventLoopGroup parent, Executor executor, IoHandlerFactory ioHandlerFactory) {
112         super(parent, executor, false,
113                 ObjectUtil.checkNotNull(ioHandlerFactory, "ioHandlerFactory").isChangingThreadSupported());
114         this.maxTaskProcessingQuantumNs = DEFAULT_MAX_TASK_PROCESSING_QUANTUM_NS;
115         this.ioHandler = ioHandlerFactory.newHandler(this);
116     }
117 
118     /**
119      *  Creates a new instance
120      *
121      * @param parent                        the parent that holds this {@link IoEventLoop}.
122      * @param threadFactory                 the {@link ThreadFactory} that is used to create the underlying
123      *                                      {@link Thread}.
124      * @param ioHandlerFactory              the {@link IoHandlerFactory} that should be used to obtain {@link IoHandler}
125      *                                      to handle IO.
126      * @param maxPendingTasks               the maximum pending tasks that are allowed before
127      *                                      {@link RejectedExecutionHandler#rejected(Runnable,
128      *                                          SingleThreadEventExecutor)}
129      *                                      is called to handle it.
130      * @param rejectedExecutionHandler      the {@link RejectedExecutionHandler} that handles when more tasks are added
131      *                                      then allowed per {@code maxPendingTasks}.
132      * @param maxTaskProcessingQuantumMs    the maximum number of milliseconds that will be spent to run tasks before
133      *                                      trying to run IO again.
134      */
135     public SingleThreadIoEventLoop(IoEventLoopGroup parent, ThreadFactory threadFactory,
136                                    IoHandlerFactory ioHandlerFactory, int maxPendingTasks,
137                                    RejectedExecutionHandler rejectedExecutionHandler, long maxTaskProcessingQuantumMs) {
138         super(parent, threadFactory, false,
139                 ObjectUtil.checkNotNull(ioHandlerFactory, "ioHandlerFactory").isChangingThreadSupported(),
140                 maxPendingTasks, rejectedExecutionHandler);
141         this.maxTaskProcessingQuantumNs =
142                 ObjectUtil.checkPositiveOrZero(maxTaskProcessingQuantumMs, "maxTaskProcessingQuantumMs") == 0 ?
143                         DEFAULT_MAX_TASK_PROCESSING_QUANTUM_NS :
144                         TimeUnit.MILLISECONDS.toNanos(maxTaskProcessingQuantumMs);
145         this.ioHandler = ioHandlerFactory.newHandler(this);
146     }
147 
148     /**
149      *  Creates a new instance
150      *
151      * @param parent                        the parent that holds this {@link IoEventLoop}.
152      * @param ioHandlerFactory              the {@link IoHandlerFactory} that should be used to obtain {@link IoHandler}
153      *                                      to handle IO.
154      * @param maxPendingTasks               the maximum pending tasks that are allowed before
155      *                                      {@link RejectedExecutionHandler#rejected(Runnable,
156      *                                          SingleThreadEventExecutor)}
157      *                                      is called to handle it.
158      * @param rejectedExecutionHandler      the {@link RejectedExecutionHandler} that handles when more tasks are added
159      *                                      then allowed per {@code maxPendingTasks}.
160      * @param maxTaskProcessingQuantumMs    the maximum number of milliseconds that will be spent to run tasks before
161      *                                      trying to run IO again.
162      */
163     public SingleThreadIoEventLoop(IoEventLoopGroup parent, Executor executor,
164                                    IoHandlerFactory ioHandlerFactory, int maxPendingTasks,
165                                    RejectedExecutionHandler rejectedExecutionHandler,
166                                    long maxTaskProcessingQuantumMs) {
167         super(parent, executor, false,
168                 ObjectUtil.checkNotNull(ioHandlerFactory, "ioHandlerFactory").isChangingThreadSupported(),
169                 maxPendingTasks, rejectedExecutionHandler);
170         this.maxTaskProcessingQuantumNs =
171                 ObjectUtil.checkPositiveOrZero(maxTaskProcessingQuantumMs, "maxTaskProcessingQuantumMs") == 0 ?
172                         DEFAULT_MAX_TASK_PROCESSING_QUANTUM_NS :
173                         TimeUnit.MILLISECONDS.toNanos(maxTaskProcessingQuantumMs);
174         this.ioHandler = ioHandlerFactory.newHandler(this);
175     }
176 
177     /**
178      *
179      *  Creates a new instance
180      *
181      * @param parent                    the parent that holds this {@link IoEventLoop}.
182      * @param executor                  the {@link Executor} that is used for dispatching the work.
183      * @param ioHandlerFactory          the {@link IoHandlerFactory} that should be used to obtain {@link IoHandler}
184      *                                  to handle IO.
185      * @param taskQueue                 the {@link Queue} used for storing pending tasks.
186      * @param tailTaskQueue             the {@link Queue} used for storing tail pending tasks.
187      * @param rejectedExecutionHandler  the {@link RejectedExecutionHandler} that handles when more tasks are added
188      *                                  then allowed.
189      */
190     protected SingleThreadIoEventLoop(IoEventLoopGroup parent, Executor executor,
191                                       IoHandlerFactory ioHandlerFactory, Queue<Runnable> taskQueue,
192                                       Queue<Runnable> tailTaskQueue,
193                                       RejectedExecutionHandler rejectedExecutionHandler) {
194         super(parent, executor, false,
195                 ObjectUtil.checkNotNull(ioHandlerFactory, "ioHandlerFactory").isChangingThreadSupported(),
196                 taskQueue, tailTaskQueue, rejectedExecutionHandler);
197         this.maxTaskProcessingQuantumNs = DEFAULT_MAX_TASK_PROCESSING_QUANTUM_NS;
198         this.ioHandler = ioHandlerFactory.newHandler(this);
199     }
200 
201     @Override
202     protected void run() {
203         assert inEventLoop();
204         ioHandler.initialize();
205         do {
206             final int ioRatio = this.ioRatio;
207             final long taskQuantumNs;
208 
209             // reset before calling runIo() which is responsible for calling reportActiveIoTime(...).
210             activeIoTimeNanos = -1;
211             runIo();
212             if (ioRatio == 100 || activeIoTimeNanos == -1) {
213                 taskQuantumNs = maxTaskProcessingQuantumNs;
214             } else {
215                 // Give tasks a budget proportional to the time just spent on IO, still bounded by the
216                 // configured maximum so a burst of IO activity cannot starve the task queue indefinitely.
217                 long quantum = Math.min(maxTaskProcessingQuantumNs, activeIoTimeNanos * (100 - ioRatio) / ioRatio);
218                 if (quantum == 0) {
219                     // Ensure we always use a "deadline"
220                     taskQuantumNs = maxTaskProcessingQuantumNs;
221                 } else {
222                     taskQuantumNs = quantum;
223                 }
224             }
225             if (isShuttingDown()) {
226                 ioHandler.prepareToDestroy();
227             }
228             // Now run tasks for the computed amount of time before trying to run IO again.
229             runAllTasks(taskQuantumNs);
230 
231             // We should continue with our loop until we either confirmed a shutdown or we can suspend it.
232         } while (!confirmShutdown() && !canSuspend());
233 
234         if (isShuttingDown()) {
235             // confirmShutdown() can return true without prepareToDestroy() having run after the last registration,
236             // for example when shutdownGracefully(0, ...) is called while tasks are running. Close everything that is
237             // still registered now. The resulting close callbacks are run by the remaining confirmShutdown() calls of
238             // SingleThreadEventExecutor. Registrations that run after this point are rejected in registerForIo0.
239             ioHandler.prepareToDestroy();
240         }
241     }
242 
243     protected final IoHandler ioHandler() {
244         return ioHandler;
245     }
246 
247     /**
248      * Returns the current IO ratio. This value only affects scheduling behaviour when it's not the default
249      * value of {@code 100}, in which case each iteration's task-processing budget will be capped to the
250      * proportion of time just spent handling IO, in addition to the cap already imposed by
251      * {@code io.netty.eventLoop.maxTaskProcessingQuantumMs}.
252      */
253     public int getIoRatio() {
254         return ioRatio;
255     }
256 
257     /**
258      * Sets the percentage of the desired amount of time spent for I/O in the event loop relative to tasks.
259      * The default value is {@code 100}, which means the event loop will not attempt to balance I/O and tasks,
260      * relying purely on {@code io.netty.eventLoop.maxTaskProcessingQuantumMs} to bound the time spent running
261      * tasks. Setting a value below {@code 100}, e.g. {@code 50}, restores the pre-4.2 behaviour of giving tasks
262      * a per-iteration budget proportional to the time just spent on IO, which helps ensure that a busy task
263      * queue does not delay IO processing (and so response handling) for extended stretches of time.
264      */
265     public void setIoRatio(int ioRatio) {
266         this.ioRatio = ObjectUtil.checkInRange(ioRatio, 1, 100, "ioRatio");
267     }
268 
269     @Override
270     protected boolean canSuspend(int state) {
271         // We should only allow to suspend if there are no registrations on this loop atm.
272         return super.canSuspend(state) && numRegistrations.get() == 0;
273     }
274 
275     /**
276      * Called when IO will be processed for all the {@link IoHandle}s on this {@link SingleThreadIoEventLoop}.
277      * This method returns the number of {@link IoHandle}s for which IO was processed.
278      *
279      * This method must be called from the {@link EventLoop} thread.
280      */
281     protected int runIo() {
282         assert inEventLoop();
283         return ioHandler.run(context);
284     }
285 
286     @Override
287     public IoEventLoop next() {
288         return this;
289     }
290 
291     @Override
292     public final Future<IoRegistration> register(final IoHandle handle) {
293         Promise<IoRegistration> promise = newPromise();
294         if (inEventLoop()) {
295             registerForIo0(handle, promise);
296         } else {
297             execute(() -> registerForIo0(handle, promise));
298         }
299 
300         return promise;
301     }
302 
303     @Override
304     protected int getNumOfRegisteredChannels() {
305         return numRegistrations.get();
306     }
307 
308     private void registerForIo0(final IoHandle handle, Promise<IoRegistration> promise) {
309         assert inEventLoop();
310         if (isShuttingDown()) {
311             // Once shutdown has started a new registration might never be closed: the IO loop may already have
312             // exited (or never run again, e.g. if it was suspending when shutdown started) and the remaining tasks
313             // only run as part of confirmShutdown(). Checking the state instead of a flag set by the IO loop covers
314             // every path, as the state is updated before any task can observe the shutdown.
315             promise.setFailure(new RejectedExecutionException("IoEventLoop is shutting down"));
316             return;
317         }
318         final IoRegistration registration;
319         try {
320             registration = ioHandler.register(handle);
321         } catch (Exception e) {
322             promise.setFailure(e);
323             return;
324         }
325         numRegistrations.incrementAndGet();
326         promise.setSuccess(new IoRegistrationWrapper(registration));
327     }
328 
329     @Override
330     protected final void wakeup(boolean inEventLoop) {
331         ioHandler.wakeup();
332     }
333 
334     @Override
335     protected final void cleanup() {
336         assert inEventLoop();
337         ioHandler.destroy();
338     }
339 
340     @Override
341     public boolean isCompatible(Class<? extends IoHandle> handleType) {
342         return ioHandler.isCompatible(handleType);
343     }
344 
345     @Override
346     public boolean isIoType(Class<? extends IoHandler> handlerType) {
347         return ioHandler.getClass().equals(handlerType);
348     }
349 
350     @Override
351     protected Queue<Runnable> newTaskQueue(int maxPendingTasks) {
352         return newTaskQueue0(maxPendingTasks);
353     }
354 
355     protected static Queue<Runnable> newTaskQueue0(int maxPendingTasks) {
356         // This event loop never calls takeTask()
357         return maxPendingTasks == Integer.MAX_VALUE ? PlatformDependent.<Runnable>newMpscQueue()
358                 : PlatformDependent.<Runnable>newMpscQueue(maxPendingTasks);
359     }
360 
361     private final class IoRegistrationWrapper implements IoRegistration {
362         private final IoRegistration registration;
363         IoRegistrationWrapper(IoRegistration registration) {
364             this.registration = registration;
365         }
366 
367         @Override
368         public <T> T attachment() {
369             return registration.attachment();
370         }
371 
372         @Override
373         public long submit(IoOps ops) {
374             return registration.submit(ops);
375         }
376 
377         @Override
378         public boolean isValid() {
379             return registration.isValid();
380         }
381 
382         @Override
383         public boolean cancel() {
384             if (registration.cancel()) {
385                 numRegistrations.decrementAndGet();
386                 return true;
387             }
388             return false;
389         }
390     }
391 }