Java 7 的编译器和运行环境支持新的 try-with-resources 语句,称为 ARM 块(Automatic Resource Management) ,自动资源管理。也就是说,数据流会在 try 执行完毕后自动被关闭。
以前操作redis都是这样写的:
Jedis jedis = null;
try {
jedis = RedisPool.getMaster();
if (null == jedis) {
return CommandMessage.SystemError.value();
}
//do sth
//...
} catch (Exception ex) {
return CommandMessage.Exception.value();
} finally {
if (null != jedis)
jedis.close();
}
现在可以这样写:
try (Jedis jedis = RedisPool.getMaster()) {
if (null == jedis) {
return CommandMessage.SystemError.value();
}
//do sth
//...
} catch (Exception ex) {
return CommandMessage.Exception.value();
}
不需要你手动关闭,redis会在方法执行完后自动关闭,也就是自动调用jedis.close()方法。当然有个前提:当前的数据流必须实现 java.lang.AutoCloseable 接口。