How can I perform a get/compute lookup that is non blocking and will avoid a cache stampede.
Here is an example that will not stampede, but is blocking.
public static <KEY, VALUE> Mono<VALUE> lookupAndWrite(
Map<KEY, Signal<? extends VALUE>> cacheMap, KEY key, Mono<VALUE> mono) {
return Mono.defer(() -> Mono.just(cacheMap.computeIfAbsent(key, k ->
mono.materialize().block())).dematerialize());
}
Here is an example that will not block, but can stampede.
public static <KEY, VALUE> MonoCacheBuilderCacheMiss<KEY, VALUE> lookup(
Function<KEY, Mono<Signal<? extends VALUE>>> reader, KEY key) {
return otherSupplier -> writer -> Mono.defer(() ->
reader.apply(key)
.switchIfEmpty(otherSupplier.get()
.materialize()
.flatMap(signal -> writer.apply(key, signal)
)
)
.dematerialize());
}
Is there an approach that will not stampede or block? Would it make sense to just subscribe the blocking call on its own scheduler?