Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 25 additions & 7 deletions src/main/java/part2/cache/CachingDataStorageImpl.java
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import db.DataStorage;
import db.SlowCompletableFutureDb;

import java.util.Optional;
import java.util.concurrent.*;

public class CachingDataStorageImpl<T> implements CachingDataStorage<String, T> {
Expand Down Expand Up @@ -32,12 +33,29 @@ public CachingDataStorageImpl(DataStorage<String, T> db, int timeout, TimeUnit t

@Override
public OutdatableResult<T> 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();

CompletableFuture<T> result = new CompletableFuture<>();
CompletableFuture<Void> outdated = new CompletableFuture<>();
OutdatableResult<T> outdatableResult = new OutdatableResult<>(result, outdated);
OutdatableResult<T> cachedResult = cache.putIfAbsent(key, outdatableResult);

if (cachedResult != null)
return cachedResult;
db.get(key).whenComplete((t, thr) -> {
if (thr != null) {
result.completeExceptionally(thr);
} else {
result.complete(t);
}
scheduledExecutorService.schedule(
() -> {
cache.remove(key, outdatableResult);
outdated.complete(null);
},
timeout,
timeoutUnits);
});

return outdatableResult;
}
}