Reschedules a runnable lazily.
| 27 | * Reschedules a runnable lazily. |
| 28 | */ |
| 29 | final class Rescheduler { |
| 30 | |
| 31 | // deps |
| 32 | private final ScheduledExecutorService scheduler; |
| 33 | private final Executor serializingExecutor; |
| 34 | private final Runnable runnable; |
| 35 | |
| 36 | // state |
| 37 | private final Stopwatch stopwatch; |
| 38 | private long runAtNanos; |
| 39 | private boolean enabled; |
| 40 | private ScheduledFuture<?> wakeUp; |
| 41 | |
| 42 | Rescheduler( |
| 43 | Runnable r, |
| 44 | Executor serializingExecutor, |
| 45 | ScheduledExecutorService scheduler, |
| 46 | Stopwatch stopwatch) { |
| 47 | this.runnable = r; |
| 48 | this.serializingExecutor = serializingExecutor; |
| 49 | this.scheduler = scheduler; |
| 50 | this.stopwatch = stopwatch; |
| 51 | stopwatch.start(); |
| 52 | } |
| 53 | |
| 54 | /* must be called from the {@link #serializingExecutor} originally passed in. */ |
| 55 | void reschedule(long delay, TimeUnit timeUnit) { |
| 56 | long delayNanos = timeUnit.toNanos(delay); |
| 57 | long newRunAtNanos = nanoTime() + delayNanos; |
| 58 | enabled = true; |
| 59 | if (newRunAtNanos - runAtNanos < 0 || wakeUp == null) { |
| 60 | if (wakeUp != null) { |
| 61 | wakeUp.cancel(false); |
| 62 | } |
| 63 | wakeUp = scheduler.schedule(new FutureRunnable(), delayNanos, TimeUnit.NANOSECONDS); |
| 64 | } |
| 65 | runAtNanos = newRunAtNanos; |
| 66 | } |
| 67 | |
| 68 | // must be called from channel executor |
| 69 | void cancel(boolean permanent) { |
| 70 | enabled = false; |
| 71 | if (permanent && wakeUp != null) { |
| 72 | wakeUp.cancel(false); |
| 73 | wakeUp = null; |
| 74 | } |
| 75 | } |
| 76 | |
| 77 | private final class FutureRunnable implements Runnable { |
| 78 | @Override |
| 79 | public void run() { |
| 80 | Rescheduler.this.serializingExecutor.execute(new ChannelFutureRunnable()); |
| 81 | } |
| 82 | |
| 83 | private boolean isEnabled() { |
| 84 | return Rescheduler.this.enabled; |
| 85 | } |
| 86 | } |
nothing calls this directly
no outgoing calls
no test coverage detected