You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@lucene.apache.org by jp...@apache.org on 2022/01/10 14:40:55 UTC

[lucene] branch main updated: Simplify some exception handling with try-with-resources. (#589)

This is an automated email from the ASF dual-hosted git repository.

jpountz pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/lucene.git


The following commit(s) were added to refs/heads/main by this push:
     new 74698994 Simplify some exception handling with try-with-resources. (#589)
74698994 is described below

commit 74698994a9b46984a5be91f0571da201b3e68851
Author: Adrien Grand <jp...@gmail.com>
AuthorDate: Mon Jan 10 15:40:47 2022 +0100

    Simplify some exception handling with try-with-resources. (#589)
---
 .../lucene/analysis/ja/dict/BinaryDictionary.java  | 26 ++++------------------
 .../analysis/ja/dict/CharacterDefinition.java      | 15 ++-----------
 .../lucene/analysis/ko/dict/BinaryDictionary.java  | 20 ++++-------------
 .../lucene/analysis/AbstractAnalysisFactory.java   | 20 +++++------------
 .../apache/lucene/index/FreqProxTermsWriter.java   | 13 ++---------
 .../index/PersistentSnapshotDeletionPolicy.java    |  6 +----
 6 files changed, 19 insertions(+), 81 deletions(-)

diff --git a/lucene/analysis/kuromoji/src/java/org/apache/lucene/analysis/ja/dict/BinaryDictionary.java b/lucene/analysis/kuromoji/src/java/org/apache/lucene/analysis/ja/dict/BinaryDictionary.java
index 993ec43..f11a47e 100644
--- a/lucene/analysis/kuromoji/src/java/org/apache/lucene/analysis/ja/dict/BinaryDictionary.java
+++ b/lucene/analysis/kuromoji/src/java/org/apache/lucene/analysis/ja/dict/BinaryDictionary.java
@@ -82,16 +82,15 @@ public abstract class BinaryDictionary implements Dictionary {
       }
       this.resourcePath = resourcePath;
     }
-    InputStream mapIS = null, dictIS = null, posIS = null;
     int[] targetMapOffsets = null, targetMap = null;
     String[] posDict = null;
     String[] inflFormDict = null;
     String[] inflTypeDict = null;
     ByteBuffer buffer = null;
-    boolean success = false;
-    try {
-      mapIS = getResource(TARGETMAP_FILENAME_SUFFIX);
-      mapIS = new BufferedInputStream(mapIS);
+    try (InputStream mapIS = new BufferedInputStream(getResource(TARGETMAP_FILENAME_SUFFIX));
+        InputStream posIS = new BufferedInputStream(getResource(POSDICT_FILENAME_SUFFIX));
+        // no buffering here, as we load in one large buffer
+        InputStream dictIS = getResource(DICT_FILENAME_SUFFIX)) {
       DataInput in = new InputStreamDataInput(mapIS);
       CodecUtil.checkHeader(in, TARGETMAP_HEADER, VERSION, VERSION);
       targetMap = new int[in.readVInt()];
@@ -115,11 +114,7 @@ public abstract class BinaryDictionary implements Dictionary {
                 + ", sourceId="
                 + sourceId);
       targetMapOffsets[sourceId] = targetMap.length;
-      mapIS.close();
-      mapIS = null;
 
-      posIS = getResource(POSDICT_FILENAME_SUFFIX);
-      posIS = new BufferedInputStream(posIS);
       in = new InputStreamDataInput(posIS);
       CodecUtil.checkHeader(in, POSDICT_HEADER, VERSION, VERSION);
       int posSize = in.readVInt();
@@ -138,11 +133,7 @@ public abstract class BinaryDictionary implements Dictionary {
           inflFormDict[j] = null;
         }
       }
-      posIS.close();
-      posIS = null;
 
-      dictIS = getResource(DICT_FILENAME_SUFFIX);
-      // no buffering here, as we load in one large buffer
       in = new InputStreamDataInput(dictIS);
       CodecUtil.checkHeader(in, DICT_HEADER, VERSION, VERSION);
       final int size = in.readVInt();
@@ -152,16 +143,7 @@ public abstract class BinaryDictionary implements Dictionary {
       if (read != size) {
         throw new EOFException("Cannot read whole dictionary");
       }
-      dictIS.close();
-      dictIS = null;
       buffer = tmpBuffer.asReadOnlyBuffer();
-      success = true;
-    } finally {
-      if (success) {
-        IOUtils.close(mapIS, posIS, dictIS);
-      } else {
-        IOUtils.closeWhileHandlingException(mapIS, posIS, dictIS);
-      }
     }
 
     this.targetMap = targetMap;
diff --git a/lucene/analysis/kuromoji/src/java/org/apache/lucene/analysis/ja/dict/CharacterDefinition.java b/lucene/analysis/kuromoji/src/java/org/apache/lucene/analysis/ja/dict/CharacterDefinition.java
index d19d020..e26f9ae 100644
--- a/lucene/analysis/kuromoji/src/java/org/apache/lucene/analysis/ja/dict/CharacterDefinition.java
+++ b/lucene/analysis/kuromoji/src/java/org/apache/lucene/analysis/ja/dict/CharacterDefinition.java
@@ -22,7 +22,6 @@ import java.io.InputStream;
 import org.apache.lucene.codecs.CodecUtil;
 import org.apache.lucene.store.DataInput;
 import org.apache.lucene.store.InputStreamDataInput;
-import org.apache.lucene.util.IOUtils;
 
 /** Character category data. */
 public final class CharacterDefinition {
@@ -69,11 +68,8 @@ public final class CharacterDefinition {
   public static final byte KANJINUMERIC = (byte) CharacterClass.KANJINUMERIC.ordinal();
 
   private CharacterDefinition() throws IOException {
-    InputStream is = null;
-    boolean success = false;
-    try {
-      is = BinaryDictionary.getClassResource(getClass(), FILENAME_SUFFIX);
-      is = new BufferedInputStream(is);
+    try (InputStream is =
+        new BufferedInputStream(BinaryDictionary.getClassResource(getClass(), FILENAME_SUFFIX))) {
       final DataInput in = new InputStreamDataInput(is);
       CodecUtil.checkHeader(in, HEADER, VERSION, VERSION);
       in.readBytes(characterCategoryMap, 0, characterCategoryMap.length);
@@ -82,13 +78,6 @@ public final class CharacterDefinition {
         invokeMap[i] = (b & 0x01) != 0;
         groupMap[i] = (b & 0x02) != 0;
       }
-      success = true;
-    } finally {
-      if (success) {
-        IOUtils.close(is);
-      } else {
-        IOUtils.closeWhileHandlingException(is);
-      }
     }
   }
 
diff --git a/lucene/analysis/nori/src/java/org/apache/lucene/analysis/ko/dict/BinaryDictionary.java b/lucene/analysis/nori/src/java/org/apache/lucene/analysis/ko/dict/BinaryDictionary.java
index f002fc3..5f44ae6 100644
--- a/lucene/analysis/nori/src/java/org/apache/lucene/analysis/ko/dict/BinaryDictionary.java
+++ b/lucene/analysis/nori/src/java/org/apache/lucene/analysis/ko/dict/BinaryDictionary.java
@@ -81,12 +81,12 @@ public abstract class BinaryDictionary implements Dictionary {
       }
       this.resourcePath = resourcePath;
     }
-    InputStream mapIS = null, dictIS = null, posIS = null;
     int[] targetMapOffsets, targetMap;
     ByteBuffer buffer;
-    try {
-      mapIS = getResource(TARGETMAP_FILENAME_SUFFIX);
-      mapIS = new BufferedInputStream(mapIS);
+    try (InputStream mapIS = new BufferedInputStream(getResource(TARGETMAP_FILENAME_SUFFIX));
+        InputStream posIS = new BufferedInputStream(getResource(POSDICT_FILENAME_SUFFIX));
+        // no buffering here, as we load in one large buffer
+        InputStream dictIS = getResource(DICT_FILENAME_SUFFIX)) {
       DataInput in = new InputStreamDataInput(mapIS);
       CodecUtil.checkHeader(in, TARGETMAP_HEADER, VERSION, VERSION);
       targetMap = new int[in.readVInt()];
@@ -110,11 +110,7 @@ public abstract class BinaryDictionary implements Dictionary {
                 + ", sourceId="
                 + sourceId);
       targetMapOffsets[sourceId] = targetMap.length;
-      mapIS.close();
-      mapIS = null;
 
-      posIS = getResource(POSDICT_FILENAME_SUFFIX);
-      posIS = new BufferedInputStream(posIS);
       in = new InputStreamDataInput(posIS);
       CodecUtil.checkHeader(in, POSDICT_HEADER, VERSION, VERSION);
       int posSize = in.readVInt();
@@ -122,11 +118,7 @@ public abstract class BinaryDictionary implements Dictionary {
       for (int j = 0; j < posSize; j++) {
         posDict[j] = POS.resolveTag(in.readByte());
       }
-      posIS.close();
-      posIS = null;
 
-      dictIS = getResource(DICT_FILENAME_SUFFIX);
-      // no buffering here, as we load in one large buffer
       in = new InputStreamDataInput(dictIS);
       CodecUtil.checkHeader(in, DICT_HEADER, VERSION, VERSION);
       final int size = in.readVInt();
@@ -136,11 +128,7 @@ public abstract class BinaryDictionary implements Dictionary {
       if (read != size) {
         throw new EOFException("Cannot read whole dictionary");
       }
-      dictIS.close();
-      dictIS = null;
       buffer = tmpBuffer.asReadOnlyBuffer();
-    } finally {
-      IOUtils.closeWhileHandlingException(mapIS, posIS, dictIS);
     }
 
     this.targetMap = targetMap;
diff --git a/lucene/core/src/java/org/apache/lucene/analysis/AbstractAnalysisFactory.java b/lucene/core/src/java/org/apache/lucene/analysis/AbstractAnalysisFactory.java
index a9a5842..320677e 100644
--- a/lucene/core/src/java/org/apache/lucene/analysis/AbstractAnalysisFactory.java
+++ b/lucene/core/src/java/org/apache/lucene/analysis/AbstractAnalysisFactory.java
@@ -17,7 +17,6 @@
 package org.apache.lucene.analysis;
 
 import java.io.IOException;
-import java.io.InputStream;
 import java.io.InputStreamReader;
 import java.io.Reader;
 import java.nio.charset.CharsetDecoder;
@@ -35,7 +34,6 @@ import java.util.Set;
 import java.util.regex.Matcher;
 import java.util.regex.Pattern;
 import java.util.regex.PatternSyntaxException;
-import org.apache.lucene.util.IOUtils;
 import org.apache.lucene.util.ResourceLoader;
 import org.apache.lucene.util.ResourceLoaderAware;
 import org.apache.lucene.util.Version;
@@ -315,19 +313,13 @@ public abstract class AbstractAnalysisFactory {
       // big to start
       words = new CharArraySet(files.size() * 10, ignoreCase);
       for (String file : files) {
-        InputStream stream = null;
-        Reader reader = null;
-        try {
-          stream = loader.openResource(file.trim());
-          CharsetDecoder decoder =
-              StandardCharsets.UTF_8
-                  .newDecoder()
-                  .onMalformedInput(CodingErrorAction.REPORT)
-                  .onUnmappableCharacter(CodingErrorAction.REPORT);
-          reader = new InputStreamReader(stream, decoder);
+        CharsetDecoder decoder =
+            StandardCharsets.UTF_8
+                .newDecoder()
+                .onMalformedInput(CodingErrorAction.REPORT)
+                .onUnmappableCharacter(CodingErrorAction.REPORT);
+        try (Reader reader = new InputStreamReader(loader.openResource(file.trim()), decoder); ) {
           WordlistLoader.getSnowballWordSet(reader, words);
-        } finally {
-          IOUtils.closeWhileHandlingException(reader, stream);
         }
       }
     }
diff --git a/lucene/core/src/java/org/apache/lucene/index/FreqProxTermsWriter.java b/lucene/core/src/java/org/apache/lucene/index/FreqProxTermsWriter.java
index ca2775c..1ca589c 100644
--- a/lucene/core/src/java/org/apache/lucene/index/FreqProxTermsWriter.java
+++ b/lucene/core/src/java/org/apache/lucene/index/FreqProxTermsWriter.java
@@ -33,7 +33,6 @@ import org.apache.lucene.util.BytesRef;
 import org.apache.lucene.util.CollectionUtil;
 import org.apache.lucene.util.Counter;
 import org.apache.lucene.util.FixedBitSet;
-import org.apache.lucene.util.IOUtils;
 import org.apache.lucene.util.IntBlockPool;
 import org.apache.lucene.util.TimSorter;
 import org.apache.lucene.util.automaton.CompiledAutomaton;
@@ -127,17 +126,9 @@ final class FreqProxTermsWriter extends TermsHash {
           };
     }
 
-    FieldsConsumer consumer = state.segmentInfo.getCodec().postingsFormat().fieldsConsumer(state);
-    boolean success = false;
-    try {
+    try (FieldsConsumer consumer =
+        state.segmentInfo.getCodec().postingsFormat().fieldsConsumer(state)) {
       consumer.write(fields, norms);
-      success = true;
-    } finally {
-      if (success) {
-        IOUtils.close(consumer);
-      } else {
-        IOUtils.closeWhileHandlingException(consumer);
-      }
     }
   }
 
diff --git a/lucene/core/src/java/org/apache/lucene/index/PersistentSnapshotDeletionPolicy.java b/lucene/core/src/java/org/apache/lucene/index/PersistentSnapshotDeletionPolicy.java
index c00a115..852adb9 100644
--- a/lucene/core/src/java/org/apache/lucene/index/PersistentSnapshotDeletionPolicy.java
+++ b/lucene/core/src/java/org/apache/lucene/index/PersistentSnapshotDeletionPolicy.java
@@ -170,9 +170,8 @@ public class PersistentSnapshotDeletionPolicy extends SnapshotDeletionPolicy {
 
   private synchronized void persist() throws IOException {
     String fileName = SNAPSHOTS_PREFIX + nextWriteGen;
-    IndexOutput out = dir.createOutput(fileName, IOContext.DEFAULT);
     boolean success = false;
-    try {
+    try (IndexOutput out = dir.createOutput(fileName, IOContext.DEFAULT)) {
       CodecUtil.writeHeader(out, CODEC_NAME, VERSION_CURRENT);
       out.writeVInt(refCounts.size());
       for (Entry<Long, Integer> ent : refCounts.entrySet()) {
@@ -182,10 +181,7 @@ public class PersistentSnapshotDeletionPolicy extends SnapshotDeletionPolicy {
       success = true;
     } finally {
       if (!success) {
-        IOUtils.closeWhileHandlingException(out);
         IOUtils.deleteFilesIgnoringExceptions(dir, fileName);
-      } else {
-        IOUtils.close(out);
       }
     }