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

huxing pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/incubator-dubbo.git


The following commit(s) were added to refs/heads/master by this push:
     new 19c1af8  [Enhancement] Replace explicit resource management with 
try-with-resource (#3281)
19c1af8 is described below

commit 19c1af845d51f3537d95ed645e1a7388a7989aa1
Author: Song Kun <[email protected]>
AuthorDate: Wed Jan 30 10:05:01 2019 +0800

    [Enhancement] Replace explicit resource management with try-with-resource 
(#3281)
---
 .../org/apache/dubbo/config/ReferenceConfig.java   | 13 +------
 .../org/apache/dubbo/config/ServiceConfig.java     | 18 +++------
 .../spring/status/DataSourceStatusChecker.java     | 31 ++++++---------
 .../metadata/support/AbstractMetadataReport.java   | 44 ++++++++--------------
 .../integration/MetadataReportServiceTest.java     |  8 +---
 .../main/java/org/apache/dubbo/qos/textui/TKv.java |  8 +---
 .../java/org/apache/dubbo/qos/textui/TTable.java   |  5 +--
 .../java/org/apache/dubbo/qos/textui/TTree.java    |  8 +---
 .../dubbo/registry/support/AbstractRegistry.java   | 34 ++++++-----------
 .../registry/multicast/MulticastRegistry.java      | 22 +----------
 .../apache/dubbo/registry/redis/RedisRegistry.java | 13 +++----
 .../telnet/support/command/LogTelnetHandler.java   | 10 +----
 .../rpc/protocol/redis/RedisProtocolTest.java      |  7 +---
 13 files changed, 61 insertions(+), 160 deletions(-)

diff --git 
a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ReferenceConfig.java
 
b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ReferenceConfig.java
index e435dc7..71d0573 100644
--- 
a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ReferenceConfig.java
+++ 
b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ReferenceConfig.java
@@ -593,21 +593,12 @@ public class ReferenceConfig<T> extends 
AbstractReferenceConfig {
             }
             if (resolveFile != null && resolveFile.length() > 0) {
                 Properties properties = new Properties();
-                FileInputStream fis = null;
-                try {
-                    fis = new FileInputStream(new File(resolveFile));
+                try (FileInputStream fis = new FileInputStream(new 
File(resolveFile))) {
                     properties.load(fis);
                 } catch (IOException e) {
                     throw new IllegalStateException("Failed to load " + 
resolveFile + ", cause: " + e.getMessage(), e);
-                } finally {
-                    try {
-                        if (null != fis) {
-                            fis.close();
-                        }
-                    } catch (IOException e) {
-                        logger.warn(e.getMessage(), e);
-                    }
                 }
+
                 resolve = properties.getProperty(interfaceName);
             }
         }
diff --git 
a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ServiceConfig.java
 
b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ServiceConfig.java
index 8868c46..3a85ac8 100644
--- 
a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ServiceConfig.java
+++ 
b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ServiceConfig.java
@@ -626,19 +626,11 @@ public class ServiceConfig<T> extends 
AbstractServiceConfig {
                                 // skip multicast registry since we cannot 
connect to it via Socket
                                 continue;
                             }
-                            try {
-                                Socket socket = new Socket();
-                                try {
-                                    SocketAddress addr = new 
InetSocketAddress(registryURL.getHost(), registryURL.getPort());
-                                    socket.connect(addr, 1000);
-                                    hostToBind = 
socket.getLocalAddress().getHostAddress();
-                                    break;
-                                } finally {
-                                    try {
-                                        socket.close();
-                                    } catch (Throwable e) {
-                                    }
-                                }
+                            try (Socket socket = new Socket()) {
+                                SocketAddress addr = new 
InetSocketAddress(registryURL.getHost(), registryURL.getPort());
+                                socket.connect(addr, 1000);
+                                hostToBind = 
socket.getLocalAddress().getHostAddress();
+                                break;
                             } catch (Exception e) {
                                 logger.warn(e.getMessage(), e);
                             }
diff --git 
a/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/status/DataSourceStatusChecker.java
 
b/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/status/DataSourceStatusChecker.java
index b777f63..3fba654 100644
--- 
a/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/status/DataSourceStatusChecker.java
+++ 
b/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/status/DataSourceStatusChecker.java
@@ -67,27 +67,20 @@ public class DataSourceStatusChecker implements 
StatusChecker {
                 buf.append(", ");
             }
             buf.append(entry.getKey());
-            try {
-                Connection connection = dataSource.getConnection();
-                try {
-                    DatabaseMetaData metaData = connection.getMetaData();
-                    ResultSet resultSet = metaData.getTypeInfo();
-                    try {
-                        if (!resultSet.next()) {
-                            level = Status.Level.ERROR;
-                        }
-                    } finally {
-                        resultSet.close();
+
+            try (Connection connection = dataSource.getConnection()) {
+                DatabaseMetaData metaData = connection.getMetaData();
+                try (ResultSet resultSet = metaData.getTypeInfo()) {
+                    if (!resultSet.next()) {
+                        level = Status.Level.ERROR;
                     }
-                    buf.append(metaData.getURL());
-                    buf.append("(");
-                    buf.append(metaData.getDatabaseProductName());
-                    buf.append("-");
-                    buf.append(metaData.getDatabaseProductVersion());
-                    buf.append(")");
-                } finally {
-                    connection.close();
                 }
+                buf.append(metaData.getURL());
+                buf.append("(");
+                buf.append(metaData.getDatabaseProductName());
+                buf.append("-");
+                buf.append(metaData.getDatabaseProductVersion());
+                buf.append(")");
             } catch (Throwable e) {
                 logger.warn(e.getMessage(), e);
                 return new Status(level, e.getMessage());
diff --git 
a/dubbo-metadata-report/dubbo-metadata-report-api/src/main/java/org/apache/dubbo/metadata/support/AbstractMetadataReport.java
 
b/dubbo-metadata-report/dubbo-metadata-report-api/src/main/java/org/apache/dubbo/metadata/support/AbstractMetadataReport.java
index f1bff8a..f6bcad7 100644
--- 
a/dubbo-metadata-report/dubbo-metadata-report-api/src/main/java/org/apache/dubbo/metadata/support/AbstractMetadataReport.java
+++ 
b/dubbo-metadata-report/dubbo-metadata-report-api/src/main/java/org/apache/dubbo/metadata/support/AbstractMetadataReport.java
@@ -134,27 +134,23 @@ public abstract class AbstractMetadataReport implements 
MetadataReport {
             if (!lockfile.exists()) {
                 lockfile.createNewFile();
             }
-            RandomAccessFile raf = new RandomAccessFile(lockfile, "rw");
-            try {
-                try (FileChannel channel = raf.getChannel()) {
-                    FileLock lock = channel.tryLock();
-                    if (lock == null) {
-                        throw new IOException("Can not lock the metadataReport 
cache file " + file.getAbsolutePath() + ", ignore and retry later, maybe multi 
java process use the file, please config: dubbo.metadata.file=xxx.properties");
+            try (RandomAccessFile raf = new RandomAccessFile(lockfile, "rw");
+                 FileChannel channel = raf.getChannel()) {
+                FileLock lock = channel.tryLock();
+                if (lock == null) {
+                    throw new IOException("Can not lock the metadataReport 
cache file " + file.getAbsolutePath() + ", ignore and retry later, maybe multi 
java process use the file, please config: dubbo.metadata.file=xxx.properties");
+                }
+                // Save
+                try {
+                    if (!file.exists()) {
+                        file.createNewFile();
                     }
-                    // Save
-                    try {
-                        if (!file.exists()) {
-                            file.createNewFile();
-                        }
-                        try (FileOutputStream outputFile = new 
FileOutputStream(file)) {
-                            properties.store(outputFile, "Dubbo metadataReport 
Cache");
-                        }
-                    } finally {
-                        lock.release();
+                    try (FileOutputStream outputFile = new 
FileOutputStream(file)) {
+                        properties.store(outputFile, "Dubbo metadataReport 
Cache");
                     }
+                } finally {
+                    lock.release();
                 }
-            } finally {
-                raf.close();
             }
         } catch (Throwable e) {
             if (version < lastCacheChanged.get()) {
@@ -168,23 +164,13 @@ public abstract class AbstractMetadataReport implements 
MetadataReport {
 
     void loadProperties() {
         if (file != null && file.exists()) {
-            InputStream in = null;
-            try {
-                in = new FileInputStream(file);
+            try (InputStream in = new FileInputStream(file)) {
                 properties.load(in);
                 if (logger.isInfoEnabled()) {
                     logger.info("Load service store file " + file + ", data: " 
+ properties);
                 }
             } catch (Throwable e) {
                 logger.warn("Failed to load service store file " + file, e);
-            } finally {
-                if (in != null) {
-                    try {
-                        in.close();
-                    } catch (IOException e) {
-                        logger.warn(e.getMessage(), e);
-                    }
-                }
             }
         }
     }
diff --git 
a/dubbo-metadata-report/dubbo-metadata-report-api/src/test/java/org/apache/dubbo/metadata/integration/MetadataReportServiceTest.java
 
b/dubbo-metadata-report/dubbo-metadata-report-api/src/test/java/org/apache/dubbo/metadata/integration/MetadataReportServiceTest.java
index 88f1bee..b0e24b5 100644
--- 
a/dubbo-metadata-report/dubbo-metadata-report-api/src/test/java/org/apache/dubbo/metadata/integration/MetadataReportServiceTest.java
+++ 
b/dubbo-metadata-report/dubbo-metadata-report-api/src/test/java/org/apache/dubbo/metadata/integration/MetadataReportServiceTest.java
@@ -40,13 +40,7 @@ public class MetadataReportServiceTest {
 
     @BeforeEach
     public void before() {
-
-        metadataReportService1 = MetadataReportService.instance(new 
Supplier<URL>() {
-            @Override
-            public URL get() {
-                return url;
-            }
-        });
+        metadataReportService1 = MetadataReportService.instance(() -> url);
     }
 
     @Test
diff --git 
a/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/textui/TKv.java 
b/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/textui/TKv.java
index 5bf517c..483b3f6 100644
--- a/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/textui/TKv.java
+++ b/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/textui/TKv.java
@@ -59,9 +59,7 @@ public class TKv implements TComponent {
 
     private String filterEmptyLine(String content) {
         final StringBuilder sb = new StringBuilder();
-        Scanner scanner = null;
-        try {
-            scanner = new Scanner(content);
+        try (Scanner scanner = new Scanner(content)) {
             while (scanner.hasNextLine()) {
                 String line = scanner.nextLine();
                 if (line != null) {
@@ -73,10 +71,6 @@ public class TKv implements TComponent {
                 }
                 sb.append(line).append(System.lineSeparator());
             }
-        } finally {
-            if (null != scanner) {
-                scanner.close();
-            }
         }
 
         return sb.toString();
diff --git 
a/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/textui/TTable.java 
b/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/textui/TTable.java
index 051ae62..c9a6715 100644
--- 
a/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/textui/TTable.java
+++ 
b/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/textui/TTable.java
@@ -419,13 +419,10 @@ public class TTable implements TComponent {
      */
     private static int width(String string) {
         int maxWidth = 0;
-        final Scanner scanner = new Scanner(new StringReader(string));
-        try {
+        try (Scanner scanner = new Scanner(new StringReader(string))) {
             while (scanner.hasNextLine()) {
                 maxWidth = max(length(scanner.nextLine()), maxWidth);
             }
-        } finally {
-            scanner.close();
         }
         return maxWidth;
     }
diff --git 
a/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/textui/TTree.java 
b/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/textui/TTree.java
index b4aaf98..50dca53 100644
--- 
a/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/textui/TTree.java
+++ 
b/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/textui/TTree.java
@@ -78,16 +78,14 @@ public class TTree implements TComponent {
                     treeSB.append(costPrefix);
                 }
 
-                final Scanner scanner = new Scanner(new 
StringReader(node.data.toString()));
-                try {
+                try (Scanner scanner = new Scanner(new 
StringReader(node.data.toString()))) {
                     boolean isFirst = true;
                     while (scanner.hasNextLine()) {
                         if (isFirst) {
                             treeSB.append(scanner.nextLine()).append("\n");
                             isFirst = false;
                         } else {
-                            treeSB
-                                    .append(prefix)
+                            treeSB.append(prefix)
                                     .append(repeat(' ', stepStringLength))
                                     .append(hasChild ? "|" : EMPTY)
                                     .append(repeat(' ', costPrefixLength))
@@ -95,8 +93,6 @@ public class TTree implements TComponent {
                                     .append(System.lineSeparator());
                         }
                     }
-                } finally {
-                    scanner.close();
                 }
 
             }
diff --git 
a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/support/AbstractRegistry.java
 
b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/support/AbstractRegistry.java
index de58981..bc119d0 100644
--- 
a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/support/AbstractRegistry.java
+++ 
b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/support/AbstractRegistry.java
@@ -155,33 +155,23 @@ public abstract class AbstractRegistry implements 
Registry {
             if (!lockfile.exists()) {
                 lockfile.createNewFile();
             }
-            RandomAccessFile raf = new RandomAccessFile(lockfile, "rw");
-            try {
-                FileChannel channel = raf.getChannel();
+            try (RandomAccessFile raf = new RandomAccessFile(lockfile, "rw");
+                 FileChannel channel = raf.getChannel()) {
+                FileLock lock = channel.tryLock();
+                if (lock == null) {
+                    throw new IOException("Can not lock the registry cache 
file " + file.getAbsolutePath() + ", ignore and retry later, maybe multi java 
process use the file, please config: dubbo.registry.file=xxx.properties");
+                }
+                // Save
                 try {
-                    FileLock lock = channel.tryLock();
-                    if (lock == null) {
-                        throw new IOException("Can not lock the registry cache 
file " + file.getAbsolutePath() + ", ignore and retry later, maybe multi java 
process use the file, please config: dubbo.registry.file=xxx.properties");
+                    if (!file.exists()) {
+                        file.createNewFile();
                     }
-                    // Save
-                    try {
-                        if (!file.exists()) {
-                            file.createNewFile();
-                        }
-                        FileOutputStream outputFile = new 
FileOutputStream(file);
-                        try {
-                            properties.store(outputFile, "Dubbo Registry 
Cache");
-                        } finally {
-                            outputFile.close();
-                        }
-                    } finally {
-                        lock.release();
+                    try (FileOutputStream outputFile = new 
FileOutputStream(file)) {
+                        properties.store(outputFile, "Dubbo Registry Cache");
                     }
                 } finally {
-                    channel.close();
+                    lock.release();
                 }
-            } finally {
-                raf.close();
             }
         } catch (Throwable e) {
             if (version < lastCacheChanged.get()) {
diff --git 
a/dubbo-registry/dubbo-registry-multicast/src/main/java/org/apache/dubbo/registry/multicast/MulticastRegistry.java
 
b/dubbo-registry/dubbo-registry-multicast/src/main/java/org/apache/dubbo/registry/multicast/MulticastRegistry.java
index 338b556..3223532 100644
--- 
a/dubbo-registry/dubbo-registry-multicast/src/main/java/org/apache/dubbo/registry/multicast/MulticastRegistry.java
+++ 
b/dubbo-registry/dubbo-registry-multicast/src/main/java/org/apache/dubbo/registry/multicast/MulticastRegistry.java
@@ -167,33 +167,15 @@ public class MulticastRegistry extends FailbackRegistry {
         if (!url.getParameter(Constants.DYNAMIC_KEY, true) || url.getPort() <= 
0 || Constants.CONSUMER_PROTOCOL.equals(url.getProtocol()) || 
Constants.ROUTE_PROTOCOL.equals(url.getProtocol()) || 
Constants.OVERRIDE_PROTOCOL.equals(url.getProtocol())) {
             return false;
         }
-        Socket socket = null;
-        try {
-            socket = new Socket(url.getHost(), url.getPort());
+        try (Socket socket = new Socket(url.getHost(), url.getPort())) {
         } catch (Throwable e) {
             try {
                 Thread.sleep(100);
             } catch (Throwable e2) {
             }
-            Socket socket2 = null;
-            try {
-                socket2 = new Socket(url.getHost(), url.getPort());
+            try (Socket socket2 = new Socket(url.getHost(), url.getPort())) {
             } catch (Throwable e2) {
                 return true;
-            } finally {
-                if (socket2 != null) {
-                    try {
-                        socket2.close();
-                    } catch (Throwable e2) {
-                    }
-                }
-            }
-        } finally {
-            if (socket != null) {
-                try {
-                    socket.close();
-                } catch (Throwable e) {
-                }
             }
         }
         return false;
diff --git 
a/dubbo-registry/dubbo-registry-redis/src/main/java/org/apache/dubbo/registry/redis/RedisRegistry.java
 
b/dubbo-registry/dubbo-registry-redis/src/main/java/org/apache/dubbo/registry/redis/RedisRegistry.java
index c2ce92b..f8a24b1 100644
--- 
a/dubbo-registry/dubbo-registry-redis/src/main/java/org/apache/dubbo/registry/redis/RedisRegistry.java
+++ 
b/dubbo-registry/dubbo-registry-redis/src/main/java/org/apache/dubbo/registry/redis/RedisRegistry.java
@@ -16,21 +16,20 @@
  */
 package org.apache.dubbo.registry.redis;
 
+import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
 import org.apache.dubbo.common.Constants;
 import org.apache.dubbo.common.URL;
 import org.apache.dubbo.common.logger.Logger;
 import org.apache.dubbo.common.logger.LoggerFactory;
+import org.apache.dubbo.common.utils.ArrayUtils;
 import org.apache.dubbo.common.utils.CollectionUtils;
 import org.apache.dubbo.common.utils.ExecutorUtil;
 import org.apache.dubbo.common.utils.NamedThreadFactory;
 import org.apache.dubbo.common.utils.StringUtils;
 import org.apache.dubbo.common.utils.UrlUtils;
-import org.apache.dubbo.common.utils.ArrayUtils;
 import org.apache.dubbo.registry.NotifyListener;
 import org.apache.dubbo.registry.support.FailbackRegistry;
 import org.apache.dubbo.rpc.RpcException;
-
-import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
 import redis.clients.jedis.Jedis;
 import redis.clients.jedis.JedisPool;
 import redis.clients.jedis.JedisPubSub;
@@ -225,11 +224,9 @@ public class RedisRegistry extends FailbackRegistry {
     @Override
     public boolean isAvailable() {
         for (JedisPool jedisPool : jedisPools.values()) {
-            try {
-                try (Jedis jedis = jedisPool.getResource()) {
-                    if (jedis.isConnected()) {
-                        return true; // At least one single machine is 
available.
-                    }
+            try (Jedis jedis = jedisPool.getResource()) {
+                if (jedis.isConnected()) {
+                    return true; // At least one single machine is available.
                 }
             } catch (Throwable t) {
             }
diff --git 
a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/telnet/support/command/LogTelnetHandler.java
 
b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/telnet/support/command/LogTelnetHandler.java
index bdbdebf..db531dc 100644
--- 
a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/telnet/support/command/LogTelnetHandler.java
+++ 
b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/telnet/support/command/LogTelnetHandler.java
@@ -56,10 +56,8 @@ public class LogTelnetHandler implements TelnetHandler {
 
                 if (file != null && file.exists()) {
                     try {
-                        FileInputStream fis = new FileInputStream(file);
-                        try {
-                            FileChannel filechannel = fis.getChannel();
-                            try {
+                        try (FileInputStream fis = new FileInputStream(file)) {
+                            try (FileChannel filechannel = fis.getChannel()) {
                                 size = filechannel.size();
                                 ByteBuffer bb;
                                 if (size <= showLogLength) {
@@ -78,11 +76,7 @@ public class LogTelnetHandler implements TelnetHandler {
                                 buf.append("\r\nmodified:" + (new 
SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
                                         .format(new 
Date(file.lastModified()))));
                                 buf.append("\r\nsize:" + size + "\r\n");
-                            } finally {
-                                filechannel.close();
                             }
-                        } finally {
-                            fis.close();
                         }
                     } catch (Exception e) {
                         buf.append(e.getMessage());
diff --git 
a/dubbo-rpc/dubbo-rpc-redis/src/test/java/org/apache/dubbo/rpc/protocol/redis/RedisProtocolTest.java
 
b/dubbo-rpc/dubbo-rpc-redis/src/test/java/org/apache/dubbo/rpc/protocol/redis/RedisProtocolTest.java
index fd87e40..9abada0 100644
--- 
a/dubbo-rpc/dubbo-rpc-redis/src/test/java/org/apache/dubbo/rpc/protocol/redis/RedisProtocolTest.java
+++ 
b/dubbo-rpc/dubbo-rpc-redis/src/test/java/org/apache/dubbo/rpc/protocol/redis/RedisProtocolTest.java
@@ -175,9 +175,7 @@ public class RedisProtocolTest {
 
         // jedis gets the result comparison
         JedisPool pool = new JedisPool(new GenericObjectPoolConfig(), 
"localhost", registryUrl.getPort(), 2000, password, database, (String) null);
-        Jedis jedis = null;
-        try {
-            jedis = pool.getResource();
+        try (Jedis jedis = pool.getResource()) {
             byte[] valueByte = jedis.get("key".getBytes());
             Serialization serialization = 
ExtensionLoader.getExtensionLoader(Serialization.class).getExtension(this.registryUrl.getParameter(Constants.SERIALIZATION_KEY,
 "java"));
             ObjectInput oin = serialization.deserialize(this.registryUrl, new 
ByteArrayInputStream(valueByte));
@@ -186,9 +184,6 @@ public class RedisProtocolTest {
         } catch (Exception e) {
             Assertions.fail("jedis gets the result comparison is error!");
         } finally {
-            if (jedis != null) {
-                jedis.close();
-            }
             pool.destroy();
         }
 

Reply via email to