-
Notifications
You must be signed in to change notification settings - Fork 25
Expand file tree
/
Copy pathSlowCompletableFutureDb.java
More file actions
executable file
·56 lines (46 loc) · 1.76 KB
/
SlowCompletableFutureDb.java
File metadata and controls
executable file
·56 lines (46 loc) · 1.76 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
package db;
import java.io.Closeable;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.*;
public class SlowCompletableFutureDb<T> implements DataStorage<String, T>, Closeable {
private volatile Map<String, T> values;
private final ScheduledExecutorService scheduledExecutorService =
Executors.newSingleThreadScheduledExecutor();
private int maxTimeout;
private TimeUnit timeoutUnits;
public SlowCompletableFutureDb(Map<String, T> values,
int maxTimeout,
TimeUnit timeoutUnits) {
this.values = new HashMap<>(values);
this.maxTimeout = maxTimeout;
this.timeoutUnits = timeoutUnits;
}
public SlowCompletableFutureDb(Map<String, T> values) {
this(values, 100, TimeUnit.MILLISECONDS);
}
public CompletableFuture<T> get(String key) {
final T value = values.get(key);
final CompletableFuture<T> result = new CompletableFuture<T>();
final int timeout = ThreadLocalRandom.current().nextInt(maxTimeout);
scheduledExecutorService.schedule(
() -> result.complete(value),
timeout,
timeoutUnits);
return result;
}
public void setValues(Map<String, T> values) {
this.values = new HashMap<>(values);
}
@Override
public void close() throws IOException {
scheduledExecutorService.shutdown();
scheduledExecutorService.shutdownNow();
try {
scheduledExecutorService.awaitTermination(5, TimeUnit.SECONDS);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}