Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

part2 #47

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
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;
}
}