-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDelay.java
More file actions
68 lines (54 loc) · 1.81 KB
/
Delay.java
File metadata and controls
68 lines (54 loc) · 1.81 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
57
58
59
60
61
62
63
64
65
66
67
68
package com.eternalcode.commons.delay;
import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import org.jspecify.annotations.Nullable;
import java.time.Duration;
import java.time.Instant;
import java.util.function.Supplier;
public class Delay<T> {
private final Cache<T, Instant> cache;
private final Supplier<Duration> defaultDelay;
private Delay(Supplier<Duration> defaultDelay) {
if (defaultDelay == null) {
throw new IllegalArgumentException("defaultDelay cannot be null");
}
this.defaultDelay = defaultDelay;
this.cache = Caffeine.newBuilder()
.expireAfter(new InstantExpiry<T>())
.build();
}
public static <T> Delay<T> withDefault(Supplier<Duration> defaultDelay) {
return new Delay<>(defaultDelay);
}
public void markDelay(T key, Duration delay) {
if (delay.isZero() || delay.isNegative()) {
this.cache.invalidate(key);
return;
}
this.cache.put(key, Instant.now().plus(delay));
}
public void markDelay(T key) {
this.markDelay(key, this.defaultDelay.get());
}
public void unmarkDelay(T key) {
this.cache.invalidate(key);
}
public boolean hasDelay(T key) {
Instant delayExpireMoment = this.getExpireAt(key);
if (delayExpireMoment == null) {
return false;
}
return Instant.now().isBefore(delayExpireMoment);
}
public Duration getRemaining(T key) {
Instant expireAt = this.getExpireAt(key);
if (expireAt == null) {
return Duration.ZERO;
}
return Duration.between(Instant.now(), expireAt);
}
@Nullable
private Instant getExpireAt(T key) {
return this.cache.getIfPresent(key);
}
}