View Javadoc
1   /*
2    * Copyright 2016 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.netty5.util.concurrent;
17  
18  import io.netty5.util.internal.ObjectUtil;
19  
20  import java.util.concurrent.RejectedExecutionException;
21  import java.util.concurrent.TimeUnit;
22  import java.util.concurrent.locks.LockSupport;
23  
24  /**
25   * Expose helper methods which create different {@link RejectedExecutionHandler}s.
26   */
27  public final class RejectedExecutionHandlers {
28      private static final RejectedExecutionHandler REJECT = (task, executor) -> {
29          throw new RejectedExecutionException();
30      };
31  
32      private RejectedExecutionHandlers() { }
33  
34      /**
35       * Returns a {@link RejectedExecutionHandler} that will always just throw a {@link RejectedExecutionException}.
36       */
37      public static RejectedExecutionHandler reject() {
38          return REJECT;
39      }
40  
41      /**
42       * Tries to backoff when the task can not be added due restrictions for an configured amount of time. This
43       * is only done if the task was added from outside of the event loop which means
44       * {@link EventExecutor#inEventLoop()} returns {@code false}.
45       */
46      public static RejectedExecutionHandler backoff(final int retries, long backoffAmount, TimeUnit unit) {
47          ObjectUtil.checkPositive(retries, "retries");
48          final long backOffNanos = unit.toNanos(backoffAmount);
49          return (task, executor) -> {
50              if (!executor.inEventLoop()) {
51                  for (int i = 0; i < retries; i++) {
52                      // Try to wake up the executor so it will empty its task queue.
53                      executor.wakeup(false);
54  
55                      LockSupport.parkNanos(backOffNanos);
56                      if (executor.offerTask(task)) {
57                          return;
58                      }
59                  }
60              }
61              // Either we tried to add the task from within the EventLoop or we was not able to add it even with
62              // backoff.
63              throw new RejectedExecutionException();
64          };
65      }
66  }