diff --git a/src/main/java/part2/cache/CachingDataStorageImpl.java b/src/main/java/part2/cache/CachingDataStorageImpl.java index a2ae460..4d6df22 100755 --- a/src/main/java/part2/cache/CachingDataStorageImpl.java +++ b/src/main/java/part2/cache/CachingDataStorageImpl.java @@ -1,7 +1,6 @@ package part2.cache; import db.DataStorage; -import db.SlowCompletableFutureDb; import java.util.concurrent.*; @@ -38,6 +37,22 @@ 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 outdatableResult = new OutdatableResult<>(result, outdated); + OutdatableResult cachedResult = cache.putIfAbsent(key, outdatableResult); + + if (cachedResult != null) return cachedResult; + + db.get(key).whenComplete((t, throwable) -> { + if (throwable != null) + result.completeExceptionally(throwable); + else result.complete(t); + scheduledExecutorService.schedule(() -> { + cache.remove(key, outdatableResult); + outdated.complete(null); + }, timeout, timeoutUnits); + }); + return outdatableResult; } }