gpt4 book ai didi

对象生命周期结束的 Java 技术

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:10:11 27 4
gpt4 key购买 nike

经验丰富的 Java 新手,寻求您的智慧:

如果无法确保在对象超出范围时执行某些特定的 block 代码,那么还有哪些其他方法可以提供相同的功能?(看起来 finalize 显然不是那个意思)

一个典型的例子是作用域锁惯用语:

void method()
{
// Thread-unsafe operations {...}

{ // <- New scope
// Give a mutex to the lock
ScopedLock lock(m_mutex);

// thread safe operations {...}

if (...) return; // Mutex is unlocked automatically on return

// thread safe operations {...}

} // <- End of scope, Mutex is unlocked automatically

// Thread-unsafe operations {...}
}

我可以理解,在 Java 中,如果您没有明确调用某些代码,将不赞成执行它。但是我发现能够在对象的生命周期结束时强制执行一些代码是一个非常强大的功能,可以确保您的类被客户端代码合理地使用。谢谢

最佳答案

通常 - 如果您需要实际关闭/处置资源,那么我们鼓励使用 try{} finally{} 结构。

  // The old way - using try/finally
Statement stmt = con.createStatement();
try {
ResultSet rs = stmt.executeQuery(query);
while (rs.next()) {
// ...
}
} catch (SQLException e) {
// Whatever ... .
} finally {
// Be sure to close the statement.
if (stmt != null) {
stmt.close();
}
}

最近的 java 版本有 AutoCloseable您可以使用 with 机制的接口(interface)。全部Closeable对象自动 AutoCloseable

  // Example of what is called try-with
try (Statement stmt = con.createStatement()) {
ResultSet rs = stmt.executeQuery(query);
while (rs.next()) {
// ...
}
} catch (SQLException e) {
// Whatever ... stmt will be closed.
}

关于对象生命周期结束的 Java 技术,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18336484/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com