CavalliumDBEngine/src/main/java/it/cavallium/dbengine/database/disk/LuceneIndexSnapshot.java

67 lines
1.7 KiB
Java
Raw Normal View History

2020-12-07 22:15:18 +01:00
package it.cavallium.dbengine.database.disk;
import java.io.IOException;
2021-09-25 13:06:24 +02:00
import java.util.concurrent.Executor;
import java.util.concurrent.ForkJoinPool;
2020-12-07 22:15:18 +01:00
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexCommit;
import org.apache.lucene.search.IndexSearcher;
2021-09-25 13:06:24 +02:00
import org.jetbrains.annotations.Nullable;
2020-12-07 22:15:18 +01:00
2021-02-03 14:37:02 +01:00
@SuppressWarnings("unused")
2020-12-07 22:15:18 +01:00
public class LuceneIndexSnapshot {
private final IndexCommit snapshot;
private boolean initialized;
private boolean failed;
private boolean closed;
private IndexSearcher indexSearcher;
public LuceneIndexSnapshot(IndexCommit snapshot) {
this.snapshot = snapshot;
}
public IndexCommit getSnapshot() {
return snapshot;
}
/**
* Can be called only if the snapshot has not been closed
* @throws IllegalStateException if closed or failed
*/
2021-09-25 13:06:24 +02:00
public synchronized IndexSearcher getIndexSearcher(@Nullable Executor searchExecutor) throws IllegalStateException {
openDirectoryIfNeeded(searchExecutor);
2020-12-07 22:15:18 +01:00
return indexSearcher;
}
2021-09-25 13:06:24 +02:00
private synchronized void openDirectoryIfNeeded(@Nullable Executor searchExecutor) throws IllegalStateException {
2020-12-07 22:15:18 +01:00
if (closed) {
throw new IllegalStateException("Snapshot is closed");
}
if (failed) {
throw new IllegalStateException("Snapshot failed to open");
}
if (!initialized) {
try {
2021-09-25 13:06:24 +02:00
var indexReader = DirectoryReader.open(snapshot);
indexSearcher = new IndexSearcher(indexReader, searchExecutor);
2020-12-07 22:15:18 +01:00
initialized = true;
} catch (IOException e) {
failed = true;
throw new RuntimeException(e);
}
}
}
public synchronized void close() throws IOException {
closed = true;
if (initialized && !failed) {
2021-09-25 13:06:24 +02:00
indexSearcher.getIndexReader().close();
2020-12-07 22:15:18 +01:00
indexSearcher = null;
}
}
}