Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Enhancement] Replace explicit resource management with try-with-resource #3281

Merged
merged 6 commits into from
Jan 30, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -593,21 +593,12 @@ private void resolveFile() {
}
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);
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -626,19 +626,11 @@ private String findConfigedHosts(ProtocolConfig protocolConfig, List<URL> regist
// 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);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -67,27 +67,20 @@ public Status check() {
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());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -134,27 +134,23 @@ private void doSaveProperties(long version) {
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()) {
Expand All @@ -168,23 +164,13 @@ private void doSaveProperties(long version) {

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);
}
}
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -59,9 +59,7 @@ public String rendering() {

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) {
Expand All @@ -73,10 +71,6 @@ private String filterEmptyLine(String content) {
}
sb.append(line).append(System.lineSeparator());
}
} finally {
if (null != scanner) {
scanner.close();
}
}

return sb.toString();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -419,13 +419,10 @@ private static String replaceTab(String string) {
*/
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;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -78,25 +78,21 @@ public void callback(int deep, boolean isLast, String prefix, Node node) {
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))
.append(scanner.nextLine())
.append(System.lineSeparator());
}
}
} finally {
scanner.close();
}

}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -155,33 +155,23 @@ public void doSaveProperties(long version) {
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()) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -167,33 +167,15 @@ private boolean isExpired(URL url) {
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;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -225,11 +224,9 @@ private void clean(Jedis jedis) {
@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) {
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -56,10 +56,8 @@ public String telnet(Channel channel, String message) {

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) {
Expand All @@ -78,11 +76,7 @@ public String telnet(Channel channel, String message) {
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());
Expand Down
Loading