範例
protected void finalize() throws Throwable {
Connection connection = null;
try {
Driver driver = DBUtility.getDriver();
connection = driver.connect(DBUtility.getDBURL(), DBUtility.getUserProperties());
// ...
connection.commit();
}
catch (SQLException exc) {
LogUtility.log(exc);
}
finally {
if (connection != null) {
try {
connection.close();
}
catch (SQLException exc) {
LogUtility.log(exc);
}
}
super .finalize();
}
}
解決方案
使用明確呼叫的清理方法,代替 finalize() 方法。
public void free() {
Connection connection = null;
try {
Driver driver = DBUtility.getDriver();
connection = driver.connect(DBUtility.getDBURL(), DBUtility.getUserProperties());
// 完成部分工作
connection.commit();
}
catch (SQLException exc) {
LogUtility.log(exc);
}
finally {
if (connection != null) {
try {
connection.close();
}
catch (SQLException exc) {
LogUtility.log(exc);
}
}
}
}