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

76 lines
2.0 KiB
Java
Raw Normal View History

2020-12-07 22:15:18 +01:00
package it.cavallium.dbengine.database.disk;
2022-06-30 15:06:10 +02:00
import it.cavallium.dbengine.database.DiscardingCloseable;
import it.cavallium.dbengine.lucene.LuceneCloseable;
2022-06-30 13:54:55 +02:00
import it.cavallium.dbengine.utils.SimpleResource;
2020-12-07 22:15:18 +01:00
import java.io.IOException;
import it.cavallium.dbengine.utils.DBException;
2021-09-25 13:06:24 +02:00
import java.util.concurrent.Executor;
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
public class LuceneIndexSnapshot extends SimpleResource implements DiscardingCloseable, LuceneCloseable {
2020-12-07 22:15:18 +01:00
private final IndexCommit snapshot;
private boolean initialized;
private boolean failed;
private boolean closed;
2022-06-28 13:52:21 +02:00
private DirectoryReader indexReader;
2020-12-07 22:15:18 +01:00
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);
2022-06-28 13:52:21 +02:00
this.indexReader = indexReader;
2021-09-25 13:06:24 +02:00
indexSearcher = new IndexSearcher(indexReader, searchExecutor);
2020-12-07 22:15:18 +01:00
initialized = true;
} catch (IOException e) {
failed = true;
throw new RuntimeException(e);
}
}
}
2022-06-30 13:54:55 +02:00
@Override
protected synchronized void onClose() {
2020-12-07 22:15:18 +01:00
closed = true;
if (initialized && !failed) {
2022-06-30 13:54:55 +02:00
try {
indexReader.close();
} catch (IOException e) {
throw new DBException(e);
2022-06-30 13:54:55 +02:00
}
2020-12-07 22:15:18 +01:00
indexSearcher = null;
}
}
}