From ae1c922def53d9d6fea5143fa1a427eeeab07526 Mon Sep 17 00:00:00 2001 From: Olga Li Date: Wed, 26 Jul 2017 17:28:16 +0300 Subject: [PATCH] Part2 (Olga Li) --- .../part2/cache/CachingDataStorageImpl.java | 26 ++++++++++++++++++- 1 file changed, 25 insertions(+), 1 deletion(-) diff --git a/src/main/java/part2/cache/CachingDataStorageImpl.java b/src/main/java/part2/cache/CachingDataStorageImpl.java index a2ae460..8a93abf 100755 --- a/src/main/java/part2/cache/CachingDataStorageImpl.java +++ b/src/main/java/part2/cache/CachingDataStorageImpl.java @@ -38,6 +38,30 @@ public OutdatableResult getOutdatable(String key) { // TODO don't use obtrudeException on result - just don't // TODO use remove(Object key, Object value) to remove target value // TODO Start timeout after receiving result in CompletableFuture, not after receiving CompletableFuture itself - throw new UnsupportedOperationException(); + + CompletableFuture result = new CompletableFuture<>(); + CompletableFuture outdated = new CompletableFuture<>(); + + OutdatableResult newResult = new OutdatableResult<>(result, outdated); + OutdatableResult cacheResult = cache.putIfAbsent(key, newResult); + + if (cacheResult != null) { + return cacheResult; + } + + db.get(key).whenComplete((e, t) -> { + if (t != null) { + result.completeExceptionally(t); + } else { + result.complete(e); + } + scheduledExecutorService.schedule(() -> { + cache.remove(key, newResult); + outdated.complete(null); + }, + timeout, + timeoutUnits); + }); + return newResult; } }