forked from Consensys/discovery
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathExpirationScheduler.java
More file actions
56 lines (49 loc) · 1.6 KB
/
ExpirationScheduler.java
File metadata and controls
56 lines (49 loc) · 1.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
/*
* SPDX-License-Identifier: Apache-2.0
*/
package org.ethereum.beacon.discovery.scheduler;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
/**
* Schedules `runnable` in delay which is set by constructor. When runnable is renewed by putting it
* in map again, old task is cancelled and removed. Task are equalled by the {@code Key}
*/
public class ExpirationScheduler<Key> {
private final ScheduledExecutorService scheduler;
private final long delay;
private final TimeUnit timeUnit;
private final Map<Key, ScheduledFuture<?>> expirationTasks = new ConcurrentHashMap<>();
ExpirationScheduler(long delay, TimeUnit timeUnit, final ScheduledExecutorService scheduler) {
this.delay = delay;
this.timeUnit = timeUnit;
this.scheduler = scheduler;
}
/**
* Puts scheduled task and renews (cancelling old) timeout for the task associated with the key
*
* @param key Task key
* @param runnable Task
*/
public void put(Key key, Runnable runnable) {
cancel(key);
ScheduledFuture<?> future =
scheduler.schedule(
() -> {
runnable.run();
expirationTasks.remove(key);
},
delay,
timeUnit);
expirationTasks.put(key, future);
}
/** Cancels task for key and removes it from storage */
public void cancel(Key key) {
final ScheduledFuture<?> task = expirationTasks.remove(key);
if (task != null) {
task.cancel(true);
}
}
}