1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package io.netty.util.concurrent;
17
18 import java.util.concurrent.RejectedExecutionException;
19 import java.util.concurrent.TimeUnit;
20 import java.util.concurrent.locks.LockSupport;
21
22
23
24
25 public final class RejectedExecutionHandlers {
26 private static final RejectedExecutionHandler REJECT = new RejectedExecutionHandler() {
27 @Override
28 public void rejected(Runnable task, SingleThreadEventExecutor executor) {
29 throw new RejectedExecutionException();
30 }
31 };
32
33 private RejectedExecutionHandlers() { }
34
35
36
37
38 public static RejectedExecutionHandler reject() {
39 return REJECT;
40 }
41
42
43
44
45
46
47 public static RejectedExecutionHandler backoff(final int retries, long backoffAmount, TimeUnit unit) {
48 if (retries <= 0) {
49 throw new IllegalArgumentException(retries + ": " + retries + " (expected: > 0)");
50 }
51 final long backOffNanos = unit.toNanos(backoffAmount);
52 return new RejectedExecutionHandler() {
53 @Override
54 public void rejected(Runnable task, SingleThreadEventExecutor executor) {
55 if (!executor.inEventLoop()) {
56 for (int i = 0; i < retries; i++) {
57
58 executor.wakeup(false);
59
60 LockSupport.parkNanos(backOffNanos);
61 if (executor.offerTask(task)) {
62 return;
63 }
64 }
65 }
66
67
68 throw new RejectedExecutionException();
69 }
70 };
71 }
72 }