Code cleanup

This commit is contained in:
Andrea Cavalli 2022-06-20 23:31:42 +02:00
parent d2e7c56f06
commit ea2065302a
3 changed files with 23 additions and 8 deletions

View File

@ -16,18 +16,26 @@ import reactor.core.publisher.Mono;
import reactor.util.function.Tuples;
public final class Hits<T> extends SimpleResource {
private static final Hits<?> EMPTY_HITS = new Hits<>(Flux.empty(), TotalHitsCount.of(0, true), null, false);
private Flux<T> results;
private TotalHitsCount totalHitsCount;
private Runnable onClose;
public Hits(Flux<T> results, TotalHitsCount totalHitsCount, Runnable onClose) {
this(results, totalHitsCount, onClose, true);
}
private Hits(Flux<T> results, TotalHitsCount totalHitsCount, Runnable onClose, boolean canClose) {
super(canClose);
this.results = results;
this.totalHitsCount = totalHitsCount;
this.onClose = onClose;
}
@SuppressWarnings("unchecked")
public static <T> Hits<T> empty() {
return new Hits<>(Flux.empty(), TotalHitsCount.of(0, true), null);
return (Hits<T>) EMPTY_HITS;
}
public static <K, V> Hits<LazyHitEntry<K, V>> withValuesLazy(Hits<LazyHitKey<K>> hits,

View File

@ -124,7 +124,7 @@ public class LuceneIndexImpl<T, U> implements LuceneIndex<T, U> {
.collectList()
.flatMap(shards -> mergeResults(queryParams, shards))
.map(this::mapResults)
.single()
.defaultIfEmpty(Hits.empty())
.doOnDiscard(LLSearchResultShard.class, SimpleResource::close)
.doOnDiscard(Hits.class, SimpleResource::close);
}
@ -153,9 +153,7 @@ public class LuceneIndexImpl<T, U> implements LuceneIndex<T, U> {
.query(query)
.timeout(Duration.ofSeconds(30))
.limit(0)
.build()), searchResultKeys -> {
return Mono.just(searchResultKeys.totalHitsCount());
}, LLUtils::finalizeResource);
.build()), searchResultKeys -> Mono.just(searchResultKeys.totalHitsCount()), LLUtils::finalizeResource);
}
@Override

View File

@ -6,20 +6,29 @@ import java.util.concurrent.atomic.AtomicBoolean;
public abstract class SimpleResource implements SafeCloseable {
private final AtomicBoolean closed = new AtomicBoolean();
private final boolean canClose;
public SimpleResource() {
canClose = true;
}
protected SimpleResource(boolean canClose) {
this.canClose = canClose;
}
@Override
public final void close() {
if (closed.compareAndSet(false, true)) {
if (canClose && closed.compareAndSet(false, true)) {
onClose();
}
}
private boolean isClosed() {
return closed.get();
return canClose && closed.get();
}
protected void ensureOpen() {
if (closed.get()) {
if (canClose && closed.get()) {
throw new IllegalStateException("Resource is closed");
}
}