try with resources
Today I learned about the try-with-resources Statement that was included with Java 7. To quote the docs:
- āA resource is an object that must be closed after the program is finished with it.ā
- āThe try-with-resources statement ensures that each resource is closed at the end of the statementā
- āAny object that implements java.lang.AutoCloseableā¦can be used as a resourceā
The basic gist here is that, when using a class that implements AutoCloseable / Closeable, we no longer have to include a finally block that closes the resource.
Hereās an example using the Apache CuratorFramework:
package com.lombardo.demo;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;
public class CuratorService {
private String zkConnectString = "localhost:2181";
private ExponentialBackoffRetry retryPolicy = new ExponentialBackoffRetry(1000, 3);
public String createNode(String path, String data) throws Exception {
// passing in a 'Closable' CuratorFramework instance to the try statement
try(CuratorFramework client = CuratorFrameworkFactory.newClient(zkConnectString, retryPolicy)) {
client.start();
return client.create().creatingParentContainersIfNeeded().forPath(path);
}
// .close() was called automatically
}
}as opposed to the finally block method:
public String createNodeOldSchool(String path, String data) throws Exception {
CuratorFramework client = CuratorFrameworkFactory.newClient(zkConnectString, retryPolicy);
try {
client.start();
return client.create().creatingParentContainersIfNeeded().forPath(path);
} finally {
client.close();
}
}