Browse Source

ZOOKEEPER-3971: Auto close resources with try catch block

Author: kamaci <furkankamaci@gmail.com>

Reviewers: Michael Han <hanm@apache.org>, Enrico Olivelli <eolivelli@gmail.com>, Christopher Tubbs

Closes #1507 from kamaci/ZOOKEEPER-3971
kamaci 4 năm trước cách đây
mục cha
commit
f06db8c91b

+ 2 - 21
zookeeper-server/src/main/java/org/apache/zookeeper/server/persistence/FileTxnLog.java

@@ -354,10 +354,7 @@ public class FileTxnLog implements TxnLog, Closeable {
         // if a log file is more recent we must scan it to find
         // the highest zxid
         long zxid = maxLog;
-        TxnIterator itr = null;
-        try {
-            FileTxnLog txn = new FileTxnLog(logDir);
-            itr = txn.read(maxLog);
+        try (FileTxnLog txn = new FileTxnLog(logDir); TxnIterator itr = txn.read(maxLog)) {
             while (true) {
                 if (!itr.next()) {
                     break;
@@ -367,22 +364,10 @@ public class FileTxnLog implements TxnLog, Closeable {
             }
         } catch (IOException e) {
             LOG.warn("Unexpected exception", e);
-        } finally {
-            close(itr);
         }
         return zxid;
     }
 
-    private void close(TxnIterator itr) {
-        if (itr != null) {
-            try {
-                itr.close();
-            } catch (IOException ioe) {
-                LOG.warn("Error closing file iterator", ioe);
-            }
-        }
-    }
-
     /**
      * commit the logs. make sure that everything hits the
      * disk
@@ -468,9 +453,7 @@ public class FileTxnLog implements TxnLog, Closeable {
      * @return true if successful false if not
      */
     public boolean truncate(long zxid) throws IOException {
-        FileTxnIterator itr = null;
-        try {
-            itr = new FileTxnIterator(this.logDir, zxid);
+        try (FileTxnIterator itr = new FileTxnIterator(this.logDir, zxid)) {
             PositionInputStream input = itr.inputStream;
             if (input == null) {
                 throw new IOException("No log files found to truncate! This could "
@@ -487,8 +470,6 @@ public class FileTxnLog implements TxnLog, Closeable {
                     LOG.warn("Unable to truncate {}", itr.logFile);
                 }
             }
-        } finally {
-            close(itr);
         }
         return true;
     }