我们已经编写了一个类,它打开了与服务器的连接。完成后,您需要告诉它commit
是否一切都成功,或者告诉它rollback
是否出现问题。所以现在我们的代码中有很多地方看起来像这样:
OurConnectionClass conn = null;
try {
conn = OurConnectionClass(parameters);
// Do some stuff here...
conn.commit();
} catch (Throwable t) {
if (conn != null) {
conn.rollback();
}
throw t;
}
如果您忘记提交或回滚,则不会立即出现问题,但最终您会耗尽连接池,然后必须找出错误的位置。
我想找到一种方法来OurConnectionClass
实现AutoClosable
,所以我可以这样做:
try (OurConnectionClass conn = new OurConnectionClass(parameters)) {
// Do some stuff here...
}
我觉得必须有办法做到这一点,但我没有看到它。AutoCloseable
只调用一个close
方法,不传递任何参数。据我所知,无法知道是否调用了 close 是因为成功到达 try 块的末尾还是抛出了异常。