-
Notifications
You must be signed in to change notification settings - Fork 25
Expand file tree
/
Copy pathListCachingDataStorage.java
More file actions
executable file
·52 lines (41 loc) · 1.81 KB
/
ListCachingDataStorage.java
File metadata and controls
executable file
·52 lines (41 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
package part3.exercise;
import part2.cache.CachingDataStorage;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.stream.Collectors;
public class ListCachingDataStorage<K, T> implements CachingDataStorage<List<K>, List<T>> {
private CachingDataStorage<K,T> storage;
public ListCachingDataStorage(CachingDataStorage<K, T> storage) {
this.storage = storage;
}
@Override
public OutdatableResult<List<T>> getOutdatable(List<K> key) {
List<OutdatableResult<T>> collect = key.stream()
.map(storage::getOutdatable)
.collect(Collectors.toList());
List<CompletableFuture<Void>> outdatables = collect.stream()
.map(OutdatableResult::getOutdated)
.collect(Collectors.toList());
List<CompletableFuture<T>> results = collect.stream()
.map(OutdatableResult::getResult)
.collect(Collectors.toList());
CompletableFuture<List<T>> listCompletableFuture = CompletableFuture.allOf(results.toArray(new CompletableFuture[0]))
.thenApply(v -> results.stream()
.map(ListCachingDataStorage::getOrNull)
.collect(Collectors.toList()));
return new OutdatableResult<>(
listCompletableFuture,
CompletableFuture.anyOf(outdatables.toArray(new CompletableFuture[0])).thenApply(v -> null)
);
}
private static <T> T getOrNull(Future<T> f) {
try {
return f.get();
} catch (InterruptedException | ExecutionException e1) {
e1.printStackTrace();
return null;
}
}
}