-
Notifications
You must be signed in to change notification settings - Fork 50
Expand file tree
/
Copy pathSimpleCache.java
More file actions
62 lines (51 loc) · 1.46 KB
/
SimpleCache.java
File metadata and controls
62 lines (51 loc) · 1.46 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
package io.ipinfo.api.cache;
import java.time.Duration;
import java.time.Instant;
import java.time.temporal.ChronoField;
import java.util.HashMap;
import java.util.Map;
public class SimpleCache implements Cache {
private final Duration duration;
private final Map<String, Payload> cache = new HashMap<>();
public SimpleCache(Duration duration) {
this.duration = duration;
}
@Override
public Object get(String key) {
Payload payload = cache.get(key);
if (payload == null || payload.hasExpired()) {
return null;
}
return payload.data;
}
@Override
public boolean set(String key, Object val) {
cache.put(key, new Payload(val, duration));
return true;
}
@Override
public boolean clear() {
cache.clear();
return true;
}
private static class Payload {
final Object data;
final Instant creation;
final Duration expiration;
Payload(Object data, Duration duration) {
this.data = data;
creation = Instant.now();
this.expiration = duration;
}
public boolean hasExpired() {
long time = expiration
.addTo(creation)
.getLong(ChronoField.INSTANT_SECONDS);
long now = System.currentTimeMillis();
return now <= time;
}
public Object getData() {
return data;
}
}
}