From 5375d252dbaa8065d29e4245970799efb1cd5c1d Mon Sep 17 00:00:00 2001 From: Iuliia_Komarova Date: Thu, 27 Jul 2017 13:49:23 +0300 Subject: [PATCH] future_part2 --- .../part2/cache/CachingDataStorageImpl.java | 31 ++++++++++++++----- 1 file changed, 23 insertions(+), 8 deletions(-) diff --git a/src/main/java/part2/cache/CachingDataStorageImpl.java b/src/main/java/part2/cache/CachingDataStorageImpl.java index a2ae460..e5a4ed0 100755 --- a/src/main/java/part2/cache/CachingDataStorageImpl.java +++ b/src/main/java/part2/cache/CachingDataStorageImpl.java @@ -1,6 +1,7 @@ package part2.cache; import db.DataStorage; +import db.SlowBlockingDb; import db.SlowCompletableFutureDb; import java.util.concurrent.*; @@ -10,7 +11,7 @@ public class CachingDataStorageImpl implements CachingDataStorage private final DataStorage db; private final int timeout; private final TimeUnit timeoutUnits; - // TODO can we use Map here? Why? + private final ConcurrentMap> cache = new ConcurrentHashMap<>(); private final ScheduledExecutorService scheduledExecutorService = Executors.newSingleThreadScheduledExecutor(new ThreadFactory() { @@ -32,12 +33,26 @@ public CachingDataStorageImpl(DataStorage db, int timeout, TimeUnit t @Override public OutdatableResult getOutdatable(String key) { - // TODO implement - // TODO use ScheduledExecutorService to remove outdated result from cache - see SlowCompletableFutureDb implementation - // TODO complete OutdatableResult::outdated after removing outdated result from cache - // 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(); + OutdatableResult result = new OutdatableResult<>(new CompletableFuture<>(), new CompletableFuture<>()); + OutdatableResult outDated = cache.putIfAbsent(key, result); + + if (outDated == null) { + db.get(key).whenComplete((res, exception) -> { + if (exception != null) { + result.getResult().completeExceptionally(exception); + } else { + result.getResult().complete(res); + } + + scheduledExecutorService.schedule(() -> { + cache.remove(get(key), result); + result.getOutdated().complete(null); + }, + timeout, + timeoutUnits); + }); + return result; + } + return outDated; } }