Apache Lucene open-source search software
Remove a few more boolean success flags (#14913)
Simon Cooper27d1272984f9
diff --git a/lucene/core/src/java/org/apache/lucene/codecs/lucene90/compressing/FieldsIndexReader.java b/lucene/core/src/java/org/apache/lucene/codecs/lucene90/compressing/FieldsIndexReader.javaindex b5631d29596..d823626c9da 100644--- a/lucene/core/src/java/org/apache/lucene/codecs/lucene90/compressing/FieldsIndexReader.java+++ b/lucene/core/src/java/org/apache/lucene/codecs/lucene90/compressing/FieldsIndexReader.java@@ -29,6 +29,7 @@ import org.apache.lucene.store.FileTypeHint;import org.apache.lucene.store.IOContext;import org.apache.lucene.store.IndexInput;import org.apache.lucene.store.RandomAccessInput;+import org.apache.lucene.util.IOUtils;import org.apache.lucene.util.packed.DirectMonotonicReader;final class FieldsIndexReader extends FieldsIndex {@@ -70,16 +71,13 @@ final class FieldsIndexReader extends FieldsIndex {dir.openInput(IndexFileNames.segmentFileName(name, suffix, extension),context.withHints(FileTypeHint.INDEX));- boolean success = false;try {CodecUtil.checkIndexHeader(indexInput, codecName + "Idx", VERSION_START, VERSION_CURRENT, id, suffix);CodecUtil.retrieveChecksum(indexInput);- success = true;- } finally {- if (success == false) {- indexInput.close();- }+ } catch (Throwable t) {+ IOUtils.closeWhileSuppressingExceptions(t, indexInput);+ throw t;}final RandomAccessInput docsSlice =indexInput.randomAccessSlice(docsStartPointer, docsEndPointer - docsStartPointer);diff --git a/lucene/core/src/java/org/apache/lucene/codecs/lucene90/compressing/FieldsIndexWriter.java b/lucene/core/src/java/org/apache/lucene/codecs/lucene90/compressing/FieldsIndexWriter.javaindex 17c15512e06..d06ca95fc87 100644--- a/lucene/core/src/java/org/apache/lucene/codecs/lucene90/compressing/FieldsIndexWriter.java+++ b/lucene/core/src/java/org/apache/lucene/codecs/lucene90/compressing/FieldsIndexWriter.java@@ -81,16 +81,13 @@ public final class FieldsIndexWriter implements Closeable {this.blockShift = blockShift;this.ioContext = ioContext;this.docsOut = dir.createTempOutput(name, codecName + "-doc_ids", ioContext);- boolean success = false;try {CodecUtil.writeHeader(docsOut, codecName + "Docs", VERSION_CURRENT);filePointersOut = dir.createTempOutput(name, codecName + "file_pointers", ioContext);CodecUtil.writeHeader(filePointersOut, codecName + "FilePointers", VERSION_CURRENT);- success = true;- } finally {- if (success == false) {- close();- }+ } catch (Throwable t) {+ IOUtils.closeWhileSuppressingExceptions(t, this);+ throw t;}}diff --git a/lucene/core/src/java/org/apache/lucene/codecs/lucene90/compressing/Lucene90CompressingStoredFieldsReader.java b/lucene/core/src/java/org/apache/lucene/codecs/lucene90/compressing/Lucene90CompressingStoredFieldsReader.javaindex a5d9e276044..9d142ba5ef2 100644--- a/lucene/core/src/java/org/apache/lucene/codecs/lucene90/compressing/Lucene90CompressingStoredFieldsReader.java+++ b/lucene/core/src/java/org/apache/lucene/codecs/lucene90/compressing/Lucene90CompressingStoredFieldsReader.java@@ -440,19 +440,16 @@ public final class Lucene90CompressingStoredFieldsReader extends StoredFieldsRea/** Reset this block so that it stores state for the block that contains the given doc id. */void reset(int docID) throws IOException {- boolean success = false;try {doReset(docID);- success = true;- } finally {- if (success == false) {- // if the read failed, set chunkDocs to 0 so that it does not- // contain any docs anymore and is not reused. This should help- // get consistent exceptions when trying to get several- // documents which are in the same corrupted block since it will- // force the header to be decoded again- chunkDocs = 0;- }+ } catch (Throwable t) {+ // if the read failed, set chunkDocs to 0 so that it does not+ // contain any docs anymore and is not reused. This should help+ // get consistent exceptions when trying to get several+ // documents which are in the same corrupted block since it will+ // force the header to be decoded again+ chunkDocs = 0;+ throw t;}}diff --git a/lucene/core/src/java/org/apache/lucene/index/ConcurrentMergeScheduler.java b/lucene/core/src/java/org/apache/lucene/index/ConcurrentMergeScheduler.javaindex 1a390d6606c..d3d47189c00 100644--- a/lucene/core/src/java/org/apache/lucene/index/ConcurrentMergeScheduler.java+++ b/lucene/core/src/java/org/apache/lucene/index/ConcurrentMergeScheduler.java@@ -578,7 +578,6 @@ public class ConcurrentMergeScheduler extends MergeScheduler {return;}- boolean success = false;try {// OK to spawn a new merge thread to handle this// merge:@@ -593,12 +592,9 @@ public class ConcurrentMergeScheduler extends MergeScheduler {newMergeThread.start();updateMergeThreads();-- success = true;- } finally {- if (!success) {- mergeSource.onMergeFinished(merge);- }+ } catch (Throwable t) {+ mergeSource.onMergeFinished(merge);+ throw t;}}}diff --git a/lucene/core/src/java/org/apache/lucene/index/DocumentsWriter.java b/lucene/core/src/java/org/apache/lucene/index/DocumentsWriter.javaindex d645ac1a1b1..3414b882f89 100644--- a/lucene/core/src/java/org/apache/lucene/index/DocumentsWriter.java+++ b/lucene/core/src/java/org/apache/lucene/index/DocumentsWriter.java@@ -209,7 +209,6 @@ final class DocumentsWriter implements Closeable, Accountable {* all currently buffered docs. This resets our state, discarding any docs added since last flush.*/synchronized void abort() throws IOException {- boolean success = false;try {deleteQueue.clear();if (infoStream.isEnabled("DW")) {@@ -224,19 +223,22 @@ final class DocumentsWriter implements Closeable, Accountable {}flushControl.abortPendingFlushes();flushControl.waitForFlush();+assert perThreadPool.size() == 0: "There are still active DWPT in the pool: " + perThreadPool.size();- success = true;- } finally {- if (success) {- assert flushControl.getFlushingBytes() == 0- : "flushingBytes has unexpected value 0 != " + flushControl.getFlushingBytes();- assert flushControl.netBytes() == 0- : "netBytes has unexpected value 0 != " + flushControl.netBytes();+ assert flushControl.getFlushingBytes() == 0+ : "flushingBytes has unexpected value 0 != " + flushControl.getFlushingBytes();+ assert flushControl.netBytes() == 0+ : "netBytes has unexpected value 0 != " + flushControl.netBytes();++ if (infoStream.isEnabled("DW")) {+ infoStream.message("DW", "done abort success=true");}+ } catch (Throwable t) {if (infoStream.isEnabled("DW")) {- infoStream.message("DW", "done abort success=" + success);+ infoStream.message("DW", "done abort success=false");}+ throw t;}}@@ -463,7 +465,6 @@ final class DocumentsWriter implements Closeable, Accountable {assert flushingDWPT != null : "Flushing DWPT must not be null";do {assert flushingDWPT.hasFlushed() == false;- boolean success = false;DocumentsWriterFlushQueue.FlushTicket ticket = null;try {assert currentFullFlushDelQueue == null@@ -514,14 +515,14 @@ final class DocumentsWriter implements Closeable, Accountable {}// flush was successful once we reached this point - new seg. has been assigned to the// ticket!- success = true;- } finally {- if (!success && ticket != null) {+ } catch (Throwable t) {+ if (ticket != null) {// In the case of a failure make sure we are making progress and// apply all the deletes since the segment flush failed since the flush// ticket could hold global deletes see FlushTicket#canPublish()ticketQueue.markTicketFailed(ticket);}+ throw t;}/** Now we are done and try to flush the ticket queue if the head of thediff --git a/lucene/core/src/java/org/apache/lucene/index/DocumentsWriterPerThread.java b/lucene/core/src/java/org/apache/lucene/index/DocumentsWriterPerThread.javaindex ddd15657fea..8b81a6a9b7f 100644--- a/lucene/core/src/java/org/apache/lucene/index/DocumentsWriterPerThread.java+++ b/lucene/core/src/java/org/apache/lucene/index/DocumentsWriterPerThread.java@@ -601,9 +601,7 @@ final class DocumentsWriterPerThread implements Accountable, Lock {IOContext context =IOContext.flush(new FlushInfo(newSegment.info.maxDoc(), newSegment.sizeInBytes()));- boolean success = false;try {-if (indexWriterConfig.getUseCompoundFile()) {Set<String> originalFiles = newSegment.info.files();// TODO: like addIndexes, we are relying on createCompoundFile to successfully cleanup...@@ -662,17 +660,14 @@ final class DocumentsWriterPerThread implements Accountable, Lock {newSegment.setDelCount(delCount);newSegment.advanceDelGen();}-- success = true;- } finally {- if (!success) {- if (infoStream.isEnabled("DWPT")) {- infoStream.message(- "DWPT",- "hit exception creating compound file for newly flushed segment "- + newSegment.info.name);- }+ } catch (Throwable t) {+ if (infoStream.isEnabled("DWPT")) {+ infoStream.message(+ "DWPT",+ "hit exception creating compound file for newly flushed segment "+ + newSegment.info.name);}+ throw t;}}diff --git a/lucene/core/src/java/org/apache/lucene/index/IndexingChain.java b/lucene/core/src/java/org/apache/lucene/index/IndexingChain.javaindex dc8d9013927..5b3a773bbe1 100644--- a/lucene/core/src/java/org/apache/lucene/index/IndexingChain.java+++ b/lucene/core/src/java/org/apache/lucene/index/IndexingChain.java@@ -368,7 +368,6 @@ final class IndexingChain implements Accountable {/** Writes all buffered points. */private void writePoints(SegmentWriteState state, Sorter.DocMap sortMap) throws IOException {PointsWriter pointsWriter = null;- boolean success = false;try {for (int i = 0; i < fieldHash.length; i++) {PerField perField = fieldHash[i];@@ -396,21 +395,17 @@ final class IndexingChain implements Accountable {}if (pointsWriter != null) {pointsWriter.finish();+ pointsWriter.close();}- success = true;- } finally {- if (success) {- IOUtils.close(pointsWriter);- } else {- IOUtils.closeWhileHandlingException(pointsWriter);- }+ } catch (Throwable t) {+ IOUtils.closeWhileSuppressingExceptions(t, pointsWriter);+ throw t;}}/** Writes all buffered doc values (called from {@link #flush}). */private void writeDocValues(SegmentWriteState state, Sorter.DocMap sortMap) throws IOException {DocValuesConsumer dvConsumer = null;- boolean success = false;try {for (int i = 0; i < fieldHash.length; i++) {PerField perField = fieldHash[i];@@ -450,13 +445,12 @@ final class IndexingChain implements Accountable {// null/"" depending on how docs landed in segments?// but we can't detect all cases, and we should leave// this behavior undefined. dv is not "schemaless": it's column-stride.- success = true;- } finally {- if (success) {- IOUtils.close(dvConsumer);- } else {- IOUtils.closeWhileHandlingException(dvConsumer);+ if (dvConsumer != null) {+ dvConsumer.close();}+ } catch (Throwable t) {+ IOUtils.closeWhileSuppressingExceptions(t, dvConsumer);+ throw t;}if (state.fieldInfos.hasDocValues() == false) {@@ -473,7 +467,6 @@ final class IndexingChain implements Accountable {}private void writeNorms(SegmentWriteState state, Sorter.DocMap sortMap) throws IOException {- boolean success = false;NormsConsumer normsConsumer = null;try {if (state.fieldInfos.hasNorms()) {@@ -494,13 +487,12 @@ final class IndexingChain implements Accountable {}}}- success = true;- } finally {- if (success) {- IOUtils.close(normsConsumer);- } else {- IOUtils.closeWhileHandlingException(normsConsumer);+ if (normsConsumer != null) {+ normsConsumer.close();}+ } catch (Throwable t) {+ IOUtils.closeWhileSuppressingExceptions(t, normsConsumer);+ throw t;}}diff --git a/lucene/core/src/java/org/apache/lucene/index/PendingDeletes.java b/lucene/core/src/java/org/apache/lucene/index/PendingDeletes.javaindex 4be3e41ad19..1844afc760e 100644--- a/lucene/core/src/java/org/apache/lucene/index/PendingDeletes.java+++ b/lucene/core/src/java/org/apache/lucene/index/PendingDeletes.java@@ -186,24 +186,21 @@ class PendingDeletes {// We can write directly to the actual name (vs to a// .tmp & renaming it) because the file is not live// until segments file is written:- boolean success = false;try {Codec codec = info.info.getCodec();codec.liveDocsFormat().writeLiveDocs(liveDocs, trackingDir, info, pendingDeleteCount, IOContext.DEFAULT);- success = true;- } finally {- if (!success) {- // Advance only the nextWriteDelGen so that a 2nd- // attempt to write will write to a new file- info.advanceNextWriteDelGen();+ } catch (Throwable t) {+ // Advance only the nextWriteDelGen so that a 2nd+ // attempt to write will write to a new file+ info.advanceNextWriteDelGen();- // Delete any partially created file(s):- for (String fileName : trackingDir.getCreatedFiles()) {- IOUtils.deleteFilesIgnoringExceptions(dir, fileName);- }+ // Delete any partially created file(s):+ for (String fileName : trackingDir.getCreatedFiles()) {+ IOUtils.deleteFilesIgnoringExceptions(dir, fileName);}+ throw t;}// If we hit an exc in the line above (eg disk full)diff --git a/lucene/core/src/java/org/apache/lucene/index/PersistentSnapshotDeletionPolicy.java b/lucene/core/src/java/org/apache/lucene/index/PersistentSnapshotDeletionPolicy.javaindex 852adb97c0d..d3fa95c1623 100644--- a/lucene/core/src/java/org/apache/lucene/index/PersistentSnapshotDeletionPolicy.java+++ b/lucene/core/src/java/org/apache/lucene/index/PersistentSnapshotDeletionPolicy.java@@ -112,20 +112,15 @@ public class PersistentSnapshotDeletionPolicy extends SnapshotDeletionPolicy {@Overridepublic synchronized IndexCommit snapshot() throws IOException {IndexCommit ic = super.snapshot();- boolean success = false;try {persist();- success = true;- } finally {- if (!success) {- try {- super.release(ic);- } catch (- @SuppressWarnings("unused")- Exception e) {- // Suppress so we keep throwing original exception- }+ } catch (Throwable t) {+ try {+ super.release(ic);+ } catch (Exception e) {+ t.addSuppressed(e);}+ throw t;}return ic;}@@ -139,20 +134,15 @@ public class PersistentSnapshotDeletionPolicy extends SnapshotDeletionPolicy {@Overridepublic synchronized void release(IndexCommit commit) throws IOException {super.release(commit);- boolean success = false;try {persist();- success = true;- } finally {- if (!success) {- try {- incRef(commit);- } catch (- @SuppressWarnings("unused")- Exception e) {- // Suppress so we keep throwing original exception- }+ } catch (Throwable t) {+ try {+ incRef(commit);+ } catch (Exception e) {+ t.addSuppressed(e);}+ throw t;}}@@ -170,7 +160,6 @@ public class PersistentSnapshotDeletionPolicy extends SnapshotDeletionPolicy {private synchronized void persist() throws IOException {String fileName = SNAPSHOTS_PREFIX + nextWriteGen;- boolean success = false;try (IndexOutput out = dir.createOutput(fileName, IOContext.DEFAULT)) {CodecUtil.writeHeader(out, CODEC_NAME, VERSION_CURRENT);out.writeVInt(refCounts.size());@@ -178,11 +167,9 @@ public class PersistentSnapshotDeletionPolicy extends SnapshotDeletionPolicy {out.writeVLong(ent.getKey());out.writeVInt(ent.getValue());}- success = true;- } finally {- if (!success) {- IOUtils.deleteFilesIgnoringExceptions(dir, fileName);- }+ } catch (Throwable t) {+ IOUtils.deleteFilesSuppressingExceptions(t, dir, fileName);+ throw t;}dir.sync(Collections.singletonList(fileName));diff --git a/lucene/core/src/java/org/apache/lucene/index/SegmentInfos.java b/lucene/core/src/java/org/apache/lucene/index/SegmentInfos.javaindex 0418ef746f5..3d69a31aac3 100644--- a/lucene/core/src/java/org/apache/lucene/index/SegmentInfos.java+++ b/lucene/core/src/java/org/apache/lucene/index/SegmentInfos.java@@ -557,25 +557,20 @@ public final class SegmentInfos implements Cloneable, Iterable<SegmentCommitInfogeneration = nextGeneration;IndexOutput segnOutput = null;- boolean success = false;try {segnOutput = directory.createOutput(segmentFileName, IOContext.DEFAULT);write(segnOutput);segnOutput.close();directory.sync(Collections.singleton(segmentFileName));- success = true;- } finally {- if (success) {- pendingCommit = true;- } else {- // We hit an exception above; try to close the file- // but suppress any exception:- IOUtils.closeWhileHandlingException(segnOutput);- // Try not to leave a truncated segments_N file in- // the index:- IOUtils.deleteFilesIgnoringExceptions(directory, segmentFileName);- }+ pendingCommit = true;+ } catch (Throwable t) {+ // try to close the file but suppress any exception:+ IOUtils.closeWhileSuppressingExceptions(t, segnOutput);+ // Try not to leave a truncated segments_N file in+ // the index:+ IOUtils.deleteFilesSuppressingExceptions(t, directory, segmentFileName);+ throw t;}}@@ -933,7 +928,6 @@ public final class SegmentInfos implements Cloneable, Iterable<SegmentCommitInfoif (pendingCommit == false) {throw new IllegalStateException("prepareCommit was not called");}- boolean successRenameAndSync = false;final String dest;try {final String src =@@ -942,20 +936,16 @@ public final class SegmentInfos implements Cloneable, Iterable<SegmentCommitInfodir.rename(src, dest);try {dir.syncMetaData();- successRenameAndSync = true;- } finally {- if (successRenameAndSync == false) {- // at this point we already created the file but missed to sync directory let's also- // remove the- // renamed file- IOUtils.deleteFilesIgnoringExceptions(dir, dest);- }- }- } finally {- if (successRenameAndSync == false) {- // deletes pending_segments_N:- rollbackCommit(dir);+ } catch (Throwable t) {+ // at this point we already created the file but missed to sync directory let's also+ // remove the renamed file+ IOUtils.deleteFilesSuppressingExceptions(t, dir, dest);+ throw t;}+ } catch (Throwable t) {+ // deletes pending_segments_N:+ rollbackCommit(dir);+ throw t;}pendingCommit = false;diff --git a/lucene/core/src/java/org/apache/lucene/index/SegmentReader.java b/lucene/core/src/java/org/apache/lucene/index/SegmentReader.javaindex 12f48a1d98f..0d653df68ba 100644--- a/lucene/core/src/java/org/apache/lucene/index/SegmentReader.java+++ b/lucene/core/src/java/org/apache/lucene/index/SegmentReader.java@@ -95,7 +95,6 @@ public final class SegmentReader extends CodecReader {core = new SegmentCoreReaders(si.info.dir, si, context);segDocValues = new SegmentDocValues();- boolean success = false;final Codec codec = si.info.getCodec();try {if (si.hasDeletions()) {@@ -111,16 +110,14 @@ public final class SegmentReader extends CodecReader {fieldInfos = initFieldInfos();docValuesProducer = initDocValuesProducer();assert assertLiveDocs(isNRT, hardLiveDocs, liveDocs);- success = true;- } finally {+ } catch (Throwable t) {// With lock-less commits, it's entirely possible (and// fine) to hit a FileNotFound exception above. In// this case, we want to explicitly close any subset// of things that were opened so that we don't have to// wait for a GC to do so.- if (!success) {- doClose();- }+ doClose();+ throw t;}}@@ -155,15 +152,12 @@ public final class SegmentReader extends CodecReader {core.incRef();this.segDocValues = sr.segDocValues;- boolean success = false;try {fieldInfos = initFieldInfos();docValuesProducer = initDocValuesProducer();- success = true;- } finally {- if (!success) {- doClose();- }+ } catch (Throwable t) {+ doClose();+ throw t;}}diff --git a/lucene/core/src/java/org/apache/lucene/index/StandardDirectoryReader.java b/lucene/core/src/java/org/apache/lucene/index/StandardDirectoryReader.javaindex 6cf7207a151..dd6d9716c4a 100644--- a/lucene/core/src/java/org/apache/lucene/index/StandardDirectoryReader.java+++ b/lucene/core/src/java/org/apache/lucene/index/StandardDirectoryReader.java@@ -87,7 +87,6 @@ public final class StandardDirectoryReader extends DirectoryReader {SegmentInfos sis =SegmentInfos.readCommit(directory, segmentFileName, minSupportedMajorVersion);final SegmentReader[] readers = new SegmentReader[sis.size()];- boolean success = false;try {for (int i = sis.size() - 1; i >= 0; i--) {readers[i] =@@ -96,15 +95,11 @@ public final class StandardDirectoryReader extends DirectoryReader {}// This may throw CorruptIndexException if there are too many docs, so// it must be inside try clause so we close readers in that case:- DirectoryReader reader =- new StandardDirectoryReader(directory, readers, null, sis, leafSorter, false, false);- success = true;-- return reader;- } finally {- if (success == false) {- IOUtils.closeWhileHandlingException(readers);- }+ return new StandardDirectoryReader(+ directory, readers, null, sis, leafSorter, false, false);+ } catch (Throwable t) {+ IOUtils.closeWhileSuppressingExceptions(t, readers);+ throw t;}}}.run(commit);@@ -222,7 +217,6 @@ public final class StandardDirectoryReader extends DirectoryReader {+ " has invalid doc count change; likely you are re-opening a reader after illegally removing index files yourself and building a new index in their place. Use IndexWriter.deleteAll or open a new IndexWriter using OpenMode.CREATE instead");}- boolean success = false;try {SegmentReader newReader;if (oldReader == null@@ -295,11 +289,9 @@ public final class StandardDirectoryReader extends DirectoryReader {}}}- success = true;- } finally {- if (!success) {- decRefWhileHandlingException(newReaders);- }+ } catch (Throwable t) {+ decRefWhileSuppressingException(t, newReaders);+ throw t;}}return new StandardDirectoryReader(@@ -307,15 +299,13 @@ public final class StandardDirectoryReader extends DirectoryReader {}// TODO: move somewhere shared if it's useful elsewhere- private static void decRefWhileHandlingException(SegmentReader[] readers) {+ private static void decRefWhileSuppressingException(Throwable t, SegmentReader[] readers) {for (SegmentReader reader : readers) {if (reader != null) {try {reader.decRef();- } catch (- @SuppressWarnings("unused")- Throwable t) {- // Ignore so we keep throwing original exception+ } catch (Throwable rt) {+ t.addSuppressed(rt);}}}diff --git a/lucene/core/src/java/org/apache/lucene/search/SearcherManager.java b/lucene/core/src/java/org/apache/lucene/search/SearcherManager.javaindex 2d3c9f84d2d..862e62a8c5b 100644--- a/lucene/core/src/java/org/apache/lucene/search/SearcherManager.java+++ b/lucene/core/src/java/org/apache/lucene/search/SearcherManager.java@@ -248,7 +248,6 @@ public final class SearcherManager extends ReferenceManager<IndexSearcher> {public static IndexSearcher getSearcher(SearcherFactory searcherFactory, IndexReader reader, IndexReader previousReader)throws IOException {- boolean success = false;final IndexSearcher searcher;try {searcher = searcherFactory.newSearcher(reader, previousReader);@@ -260,11 +259,9 @@ public final class SearcherManager extends ReferenceManager<IndexSearcher> {+ reader+ ")");}- success = true;- } finally {- if (!success) {- reader.decRef();- }+ } catch (Throwable t) {+ reader.decRef();+ throw t;}return searcher;}diff --git a/lucene/core/src/java/org/apache/lucene/store/MMapDirectory.java b/lucene/core/src/java/org/apache/lucene/store/MMapDirectory.javaindex 77648079b04..8ca33b16d02 100644--- a/lucene/core/src/java/org/apache/lucene/store/MMapDirectory.java+++ b/lucene/core/src/java/org/apache/lucene/store/MMapDirectory.java@@ -312,35 +312,30 @@ public class MMapDirectory extends FSDirectory {// Work around for JDK-8259028: we need to unwrap our test-only file system layerspath = Unwrappable.unwrapAll(path);- boolean success = false;final boolean confined = context.hints().contains(ReadOnceHint.INSTANCE);Function<IOContext, ReadAdvice> toReadAdvice =c -> readAdviceOverride.apply(name, c).orElseGet(() -> toReadAdvice(c));final Arena arena = confined ? Arena.ofConfined() : getSharedArena(name, arenas);try (var fc = FileChannel.open(path, StandardOpenOption.READ)) {final long fileSize = fc.size();- final IndexInput in =- MemorySegmentIndexInput.newInstance(- resourceDescription,+ return MemorySegmentIndexInput.newInstance(+ resourceDescription,+ arena,+ map(arena,- map(- arena,- resourceDescription,- fc,- toReadAdvice.apply(context),- chunkSizePower,- preload.test(name, context),- fileSize),- fileSize,+ resourceDescription,+ fc,+ toReadAdvice.apply(context),chunkSizePower,- confined,- toReadAdvice);- success = true;- return in;- } finally {- if (success == false) {- arena.close();- }+ preload.test(name, context),+ fileSize),+ fileSize,+ chunkSizePower,+ confined,+ toReadAdvice);+ } catch (Throwable t) {+ arena.close();+ throw t;}}diff --git a/lucene/core/src/java/org/apache/lucene/store/NIOFSDirectory.java b/lucene/core/src/java/org/apache/lucene/store/NIOFSDirectory.javaindex b05652789cf..016be793cb2 100644--- a/lucene/core/src/java/org/apache/lucene/store/NIOFSDirectory.java+++ b/lucene/core/src/java/org/apache/lucene/store/NIOFSDirectory.java@@ -76,16 +76,11 @@ public class NIOFSDirectory extends FSDirectory {ensureCanRead(name);Path path = getDirectory().resolve(name);FileChannel fc = FileChannel.open(path, StandardOpenOption.READ);- boolean success = false;try {- final NIOFSIndexInput indexInput =- new NIOFSIndexInput("NIOFSIndexInput(path=\"" + path + "\")", fc, context);- success = true;- return indexInput;- } finally {- if (success == false) {- IOUtils.closeWhileHandlingException(fc);- }+ return new NIOFSIndexInput("NIOFSIndexInput(path=\"" + path + "\")", fc, context);+ } catch (Throwable t) {+ IOUtils.closeWhileSuppressingExceptions(t, fc);+ throw t;}}diff --git a/lucene/core/src/java/org/apache/lucene/util/OfflineSorter.java b/lucene/core/src/java/org/apache/lucene/util/OfflineSorter.javaindex c22236a7a21..39620b38df6 100644--- a/lucene/core/src/java/org/apache/lucene/util/OfflineSorter.java+++ b/lucene/core/src/java/org/apache/lucene/util/OfflineSorter.java@@ -290,7 +290,6 @@ public class OfflineSorter {// So we can remove any partially written temp files on exception:TrackingDirectoryWrapper trackingDir = new TrackingDirectoryWrapper(dir);- boolean success = false;try (ByteSequencesReader is = getReader(dir.openChecksumInput(inputFileName), inputFileName)) {while (true) {Partition part = readPartition(is);@@ -354,17 +353,14 @@ public class OfflineSorter {sortInfo.totalTimeMS = System.currentTimeMillis() - startMS;CodecUtil.checkFooter(is.in);-- success = true;-return result;} catch (InterruptedException ie) {+ IOUtils.deleteFilesSuppressingExceptions(ie, trackingDir, trackingDir.getCreatedFiles());throw new ThreadInterruptedException(ie);- } finally {- if (success == false) {- IOUtils.deleteFilesIgnoringExceptions(trackingDir, trackingDir.getCreatedFiles());- }+ } catch (Throwable t) {+ IOUtils.deleteFilesSuppressingExceptions(t, trackingDir, trackingDir.getCreatedFiles());+ throw t;}}@@ -430,7 +426,6 @@ public class OfflineSorter {if (partitionsInRAM != null) {partitionsInRAM.acquire();}- boolean success = false;try {long start = System.currentTimeMillis();SortableBytesRefArray buffer;@@ -475,12 +470,12 @@ public class OfflineSorter {}}sortInfo.readTimeMS += System.currentTimeMillis() - start;- success = true;return new Partition(buffer, exhausted);- } finally {- if (success == false && partitionsInRAM != null) {+ } catch (Throwable t) {+ if (partitionsInRAM != null) {partitionsInRAM.release();}+ throw t;}}diff --git a/lucene/core/src/java/org/apache/lucene/util/RefCount.java b/lucene/core/src/java/org/apache/lucene/util/RefCount.javaindex 3f9f09ac1c6..9945adb9e4f 100644--- a/lucene/core/src/java/org/apache/lucene/util/RefCount.java+++ b/lucene/core/src/java/org/apache/lucene/util/RefCount.java@@ -46,15 +46,12 @@ public class RefCount<T> {public final void decRef() throws IOException {final int rc = refCount.decrementAndGet();if (rc == 0) {- boolean success = false;try {release();- success = true;- } finally {- if (!success) {- // Put reference back on failure- refCount.incrementAndGet();- }+ } catch (Throwable t) {+ // Put reference back on failure+ refCount.incrementAndGet();+ throw t;}} else if (rc < 0) {throw new IllegalStateException(diff --git a/lucene/core/src/java/org/apache/lucene/util/bkd/BKDWriter.java b/lucene/core/src/java/org/apache/lucene/util/bkd/BKDWriter.javaindex 4fbd2a77693..0a1fdde57a4 100644--- a/lucene/core/src/java/org/apache/lucene/util/bkd/BKDWriter.java+++ b/lucene/core/src/java/org/apache/lucene/util/bkd/BKDWriter.java@@ -975,7 +975,6 @@ public class BKDWriter implements Closeable {new BKDRadixSelector(config, maxPointsSortInHeap, tempDir, tempFileNamePrefix);final long dataStartFP = dataOut.getFilePointer();- boolean success = false;try {final int[] parentSplits = new int[config.numIndexDims()];@@ -1000,12 +999,9 @@ public class BKDWriter implements Closeable {assert tempDir.getCreatedFiles().isEmpty();// System.out.println("write time: " + ((System.nanoTime() - t1) / (double)// TimeUnit.SECONDS.toNanos(1)) + " ms");-- success = true;- } finally {- if (success == false) {- IOUtils.deleteFilesIgnoringExceptions(tempDir, tempDir.getCreatedFiles());- }+ } catch (Throwable t) {+ IOUtils.deleteFilesSuppressingExceptions(t, tempDir, tempDir.getCreatedFiles());+ throw t;}LongValues leafBlockLongValues = leafBlockFPs.build();diff --git a/lucene/misc/src/java/org/apache/lucene/misc/index/BPIndexReorderer.java b/lucene/misc/src/java/org/apache/lucene/misc/index/BPIndexReorderer.javaindex 6507ff02500..4d2bab216b9 100644--- a/lucene/misc/src/java/org/apache/lucene/misc/index/BPIndexReorderer.java+++ b/lucene/misc/src/java/org/apache/lucene/misc/index/BPIndexReorderer.java@@ -24,6 +24,7 @@ import java.util.HashSet;import java.util.Set;import java.util.concurrent.Callable;import java.util.concurrent.Executor;+import java.util.function.IntUnaryOperator;import org.apache.lucene.codecs.CodecUtil;import org.apache.lucene.index.CodecReader;import org.apache.lucene.index.DocValues;@@ -857,51 +858,47 @@ public final class BPIndexReorderer extends AbstractBPReorderer {}final int maxDoc = reader.maxDoc();- ForwardIndex forwardIndex = null;- IndexOutput postingsOutput = null;- boolean success = false;try {- postingsOutput = trackingDir.createTempOutput("postings", "", IOContext.DEFAULT);- int numTerms = writePostings(reader, fields, trackingDir, postingsOutput, parallelism);- CodecUtil.writeFooter(postingsOutput);- postingsOutput.close();- final ForwardIndex finalForwardIndex =- forwardIndex = buildForwardIndex(trackingDir, postingsOutput.getName(), maxDoc, numTerms);- trackingDir.deleteFile(postingsOutput.getName());- postingsOutput = null;-- int[] sortedDocs = new int[maxDoc];- for (int i = 0; i < maxDoc; ++i) {- sortedDocs[i] = i;+ int numTerms;+ String postingsName;+ try (IndexOutput postingsOutput =+ trackingDir.createTempOutput("postings", "", IOContext.DEFAULT)) {+ numTerms = writePostings(reader, fields, trackingDir, postingsOutput, parallelism);+ CodecUtil.writeFooter(postingsOutput);+ postingsName = postingsOutput.getName();}- BitSet parents = null;- String parentField = reader.getFieldInfos().getParentField();- if (parentField != null) {- parents = BitSet.of(DocValues.getNumeric(reader, parentField), maxDoc);- }+ try (ForwardIndex forwardIndex =+ buildForwardIndex(trackingDir, postingsName, maxDoc, numTerms)) {+ trackingDir.deleteFile(postingsName);- try (CloseableThreadLocal<PerThreadState> threadLocal =- new CloseableThreadLocal<>() {- @Override- protected PerThreadState initialValue() {- return new PerThreadState(numTerms, finalForwardIndex.clone());- }- }) {- IntsRef docs = new IntsRef(sortedDocs, 0, sortedDocs.length);- new IndexReorderingTask(docs, new float[maxDoc], threadLocal, parents, executor, 0).call();- }+ int[] sortedDocs = new int[maxDoc];+ Arrays.setAll(sortedDocs, IntUnaryOperator.identity());++ BitSet parents = null;+ String parentField = reader.getFieldInfos().getParentField();+ if (parentField != null) {+ parents = BitSet.of(DocValues.getNumeric(reader, parentField), maxDoc);+ }++ try (CloseableThreadLocal<PerThreadState> threadLocal =+ new CloseableThreadLocal<>() {+ @Override+ protected PerThreadState initialValue() {+ return new PerThreadState(numTerms, forwardIndex.clone());+ }+ }) {+ IntsRef docs = new IntsRef(sortedDocs, 0, sortedDocs.length);+ new IndexReorderingTask(docs, new float[maxDoc], threadLocal, parents, executor, 0)+ .call();+ }- success = true;- return sortedDocs;- } finally {- if (success) {- IOUtils.close(forwardIndex);IOUtils.deleteFiles(trackingDir, trackingDir.getCreatedFiles());- } else {- IOUtils.closeWhileHandlingException(postingsOutput, forwardIndex);- IOUtils.deleteFilesIgnoringExceptions(trackingDir, trackingDir.getCreatedFiles());+ return sortedDocs;}+ } catch (Throwable t) {+ IOUtils.deleteFilesSuppressingExceptions(t, trackingDir, trackingDir.getCreatedFiles());+ throw t;}}diff --git a/lucene/misc/src/java/org/apache/lucene/misc/index/PKIndexSplitter.java b/lucene/misc/src/java/org/apache/lucene/misc/index/PKIndexSplitter.javaindex 789db6646d6..8caa9d6b5e9 100644--- a/lucene/misc/src/java/org/apache/lucene/misc/index/PKIndexSplitter.java+++ b/lucene/misc/src/java/org/apache/lucene/misc/index/PKIndexSplitter.java@@ -37,7 +37,6 @@ import org.apache.lucene.store.Directory;import org.apache.lucene.util.BitSetIterator;import org.apache.lucene.util.Bits;import org.apache.lucene.util.FixedBitSet;-import org.apache.lucene.util.IOUtils;/** Split an index based on a {@link Query}. */public class PKIndexSplitter {@@ -101,19 +100,10 @@ public class PKIndexSplitter {}public void split() throws IOException {- boolean success = false;- DirectoryReader reader = DirectoryReader.open(input);- try {+ try (DirectoryReader reader = DirectoryReader.open(input)) {// pass an individual config in here since one config can not be reused!createIndex(config1, dir1, reader, docsInFirstIndex, false);createIndex(config2, dir2, reader, docsInFirstIndex, true);- success = true;- } finally {- if (success) {- IOUtils.close(reader);- } else {- IOUtils.closeWhileHandlingException(reader);- }}}@@ -124,9 +114,7 @@ public class PKIndexSplitter {Query preserveFilter,boolean negateFilter)throws IOException {- boolean success = false;- final IndexWriter w = new IndexWriter(target, config);- try {+ try (IndexWriter w = new IndexWriter(target, config)) {final IndexSearcher searcher = new IndexSearcher(reader);searcher.setQueryCache(null);preserveFilter = searcher.rewrite(preserveFilter);@@ -139,13 +127,6 @@ public class PKIndexSplitter {subReaders[i++] = new DocumentFilteredLeafIndexReader(ctx, preserveWeight, negateFilter);}w.addIndexes(subReaders);- success = true;- } finally {- if (success) {- w.close();- } else {- IOUtils.closeWhileHandlingException(w);- }}}diff --git a/lucene/replicator/src/java/org/apache/lucene/replicator/nrt/ReplicaNode.java b/lucene/replicator/src/java/org/apache/lucene/replicator/nrt/ReplicaNode.javaindex 206c75efb75..5181ccccaf0 100644--- a/lucene/replicator/src/java/org/apache/lucene/replicator/nrt/ReplicaNode.java+++ b/lucene/replicator/src/java/org/apache/lucene/replicator/nrt/ReplicaNode.java@@ -95,8 +95,6 @@ public abstract class ReplicaNode extends Node {"Directory " + dir + " still has pending deleted files; cannot initialize IndexWriter");}- boolean success = false;-try {message("top: init replica dir=" + dir);@@ -106,15 +104,11 @@ public abstract class ReplicaNode extends Node {state = "init";deleter = new ReplicaFileDeleter(this, dir);- success = true;} catch (Throwable t) {+ IOUtils.closeWhileSuppressingExceptions(t, this);message("exc on init:");t.printStackTrace(printStream);throw t;- } finally {- if (success == false) {- IOUtils.closeWhileHandlingException(this);- }}}diff --git a/lucene/replicator/src/test/org/apache/lucene/replicator/nrt/SimpleReplicaNode.java b/lucene/replicator/src/test/org/apache/lucene/replicator/nrt/SimpleReplicaNode.javaindex 03cb5a6bfdd..b81305fff18 100644--- a/lucene/replicator/src/test/org/apache/lucene/replicator/nrt/SimpleReplicaNode.java+++ b/lucene/replicator/src/test/org/apache/lucene/replicator/nrt/SimpleReplicaNode.java@@ -343,7 +343,6 @@ class SimpleReplicaNode extends ReplicaNode {// Silly keep alive mechanism, else if e.g. we (replica node) crash, the primary// won't notice for a very long time:- boolean success = false;try {int count = 0;while (true) {@@ -367,9 +366,10 @@ class SimpleReplicaNode extends ReplicaNode {out.writeByte((byte) 1);bos.flush();- success = true;- } finally {- message("done merge copy files=" + files.keySet() + " success=" + success);+ message("done merge copy files=" + files.keySet() + " success=true");+ } catch (Throwable t) {+ message("done merge copy files=" + files.keySet() + " success=false");+ throw t;}break;diff --git a/lucene/sandbox/src/java/org/apache/lucene/sandbox/codecs/idversion/IDVersionPostingsFormat.java b/lucene/sandbox/src/java/org/apache/lucene/sandbox/codecs/idversion/IDVersionPostingsFormat.javaindex 32072af9283..de42862cc65 100644--- a/lucene/sandbox/src/java/org/apache/lucene/sandbox/codecs/idversion/IDVersionPostingsFormat.java+++ b/lucene/sandbox/src/java/org/apache/lucene/sandbox/codecs/idversion/IDVersionPostingsFormat.java@@ -80,31 +80,23 @@ public class IDVersionPostingsFormat extends PostingsFormat {@Overridepublic FieldsConsumer fieldsConsumer(SegmentWriteState state) throws IOException {PostingsWriterBase postingsWriter = new IDVersionPostingsWriter(state.liveDocs);- boolean success = false;try {- FieldsConsumer ret =- new VersionBlockTreeTermsWriter(state, postingsWriter, minTermsInBlock, maxTermsInBlock);- success = true;- return ret;- } finally {- if (!success) {- IOUtils.closeWhileHandlingException(postingsWriter);- }+ return new VersionBlockTreeTermsWriter(+ state, postingsWriter, minTermsInBlock, maxTermsInBlock);+ } catch (Throwable t) {+ IOUtils.closeWhileSuppressingExceptions(t, postingsWriter);+ throw t;}}@Overridepublic FieldsProducer fieldsProducer(SegmentReadState state) throws IOException {PostingsReaderBase postingsReader = new IDVersionPostingsReader();- boolean success = false;try {- FieldsProducer ret = new VersionBlockTreeTermsReader(postingsReader, state);- success = true;- return ret;- } finally {- if (!success) {- IOUtils.closeWhileHandlingException(postingsReader);- }+ return new VersionBlockTreeTermsReader(postingsReader, state);+ } catch (Throwable t) {+ IOUtils.closeWhileSuppressingExceptions(t, postingsReader);+ throw t;}}diff --git a/lucene/sandbox/src/java/org/apache/lucene/sandbox/codecs/idversion/VersionBlockTreeTermsReader.java b/lucene/sandbox/src/java/org/apache/lucene/sandbox/codecs/idversion/VersionBlockTreeTermsReader.javaindex 12157ca652f..7be39835bef 100644--- a/lucene/sandbox/src/java/org/apache/lucene/sandbox/codecs/idversion/VersionBlockTreeTermsReader.java+++ b/lucene/sandbox/src/java/org/apache/lucene/sandbox/codecs/idversion/VersionBlockTreeTermsReader.java@@ -64,7 +64,6 @@ public final class VersionBlockTreeTermsReader extends FieldsProducer {VersionBlockTreeTermsWriter.TERMS_EXTENSION);in = state.directory.openInput(termsFile, state.context);- boolean success = false;IndexInput indexIn = null;try {@@ -180,13 +179,10 @@ public final class VersionBlockTreeTermsReader extends FieldsProducer {}}indexIn.close();-- success = true;- } finally {- if (!success) {- // this.close() will close in:- IOUtils.closeWhileHandlingException(indexIn, this);- }+ } catch (Throwable t) {+ // this.close() will close in:+ IOUtils.closeWhileSuppressingExceptions(t, indexIn, this);+ throw t;}}diff --git a/lucene/sandbox/src/java/org/apache/lucene/sandbox/codecs/idversion/VersionBlockTreeTermsWriter.java b/lucene/sandbox/src/java/org/apache/lucene/sandbox/codecs/idversion/VersionBlockTreeTermsWriter.javaindex c416e0083c5..06dfa27e52c 100644--- a/lucene/sandbox/src/java/org/apache/lucene/sandbox/codecs/idversion/VersionBlockTreeTermsWriter.java+++ b/lucene/sandbox/src/java/org/apache/lucene/sandbox/codecs/idversion/VersionBlockTreeTermsWriter.java@@ -188,7 +188,6 @@ public final class VersionBlockTreeTermsWriter extends FieldsConsumer {IndexFileNames.segmentFileName(state.segmentInfo.name, state.segmentSuffix, TERMS_EXTENSION);out = state.directory.createOutput(termsFileName, state.context);- boolean success = false;IndexOutput indexOut = null;try {fieldInfos = state.fieldInfos;@@ -216,11 +215,9 @@ public final class VersionBlockTreeTermsWriter extends FieldsConsumer {// System.out.println("BTW.init seg=" + state.segmentName);postingsWriter.init(out, state); // have consumer write its format/header- success = true;- } finally {- if (!success) {- IOUtils.closeWhileHandlingException(out, indexOut);- }+ } catch (Throwable t) {+ IOUtils.closeWhileSuppressingExceptions(t, out, indexOut);+ throw t;}this.indexOut = indexOut;}@@ -888,9 +885,7 @@ public final class VersionBlockTreeTermsWriter extends FieldsConsumer {}closed = true;- boolean success = false;try {-final long dirStart = out.getFilePointer();final long indexDirStart = indexOut.getFilePointer();@@ -915,13 +910,10 @@ public final class VersionBlockTreeTermsWriter extends FieldsConsumer {CodecUtil.writeFooter(out);writeIndexTrailer(indexOut, indexDirStart);CodecUtil.writeFooter(indexOut);- success = true;- } finally {- if (success) {- IOUtils.close(out, indexOut, postingsWriter);- } else {- IOUtils.closeWhileHandlingException(out, indexOut, postingsWriter);- }+ IOUtils.close(out, indexOut, postingsWriter);+ } catch (Throwable t) {+ IOUtils.closeWhileSuppressingExceptions(t, out, indexOut, postingsWriter);+ throw t;}}diff --git a/lucene/suggest/src/java/org/apache/lucene/search/suggest/document/CompletionFieldsConsumer.java b/lucene/suggest/src/java/org/apache/lucene/search/suggest/document/CompletionFieldsConsumer.javaindex 73518308b36..3c96151a55e 100644--- a/lucene/suggest/src/java/org/apache/lucene/search/suggest/document/CompletionFieldsConsumer.java+++ b/lucene/suggest/src/java/org/apache/lucene/search/suggest/document/CompletionFieldsConsumer.java@@ -126,7 +126,6 @@ final class CompletionFieldsConsumer extends FieldsConsumer {String indexFile =IndexFileNames.segmentFileName(state.segmentInfo.name, state.segmentSuffix, INDEX_EXTENSION);- boolean success = false;try (IndexOutput indexOut = state.directory.createOutput(indexFile, state.context)) {delegateFieldsConsumer.close();CodecUtil.writeIndexHeader(@@ -155,11 +154,9 @@ final class CompletionFieldsConsumer extends FieldsConsumer {CodecUtil.writeFooter(indexOut);CodecUtil.writeFooter(dictOut);IOUtils.close(dictOut);- success = true;- } finally {- if (success == false) {- IOUtils.closeWhileHandlingException(dictOut, delegateFieldsConsumer);- }+ } catch (Throwable t) {+ IOUtils.closeWhileSuppressingExceptions(t, dictOut, delegateFieldsConsumer);+ throw t;}}