新加入Java的有经验的程序员正在寻求您的智慧:
如果无法确保在对象超出作用域时执行某些特定的块代码,那么还有哪些其他方法可以提供相同的功能呢?(看来“最后定稿”显然不是为了达到这个目的)
一个典型的例子是作用域锁成语:
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中,如果您没有显式地调用某些代码,那么它将被拒绝执行。但是我发现能够在对象的生命周期结束时强制执行一些代码是一个非常强大的特性,可以确保客户端代码明智地使用您的类。谢谢
发布于 2013-08-20 13:47:26
如果您想要在方法中运行一些代码,只需使用.终于..。最后一个块保证运行。或者,在Java 7中,使用"with“块。
如果您希望像运行C++的析构函数那样运行某些代码。恐怕Java中没有这样的东西。最后确定的方法不可靠,不能用于处理关键任务。Java类通常的做法是公开一个清理方法(例如,那些流类的close() ),以便客户机显式地调用这些方法来执行清理工作。
发布于 2013-08-20 13:39:59
通常,如果您需要实际关闭/处理资源,则鼓励使用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机制中使用该接口。所有合拢对象都自动为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.
}发布于 2013-08-20 13:39:57
从Java 7开始,就有了自动资源管理。如果您的锁在您的控制之下,那么让它实现AutoCloseable。不幸的是,java.util.concurrent锁没有实现这个接口。这里有一个很好的参考资料给出了详细的说明。
https://stackoverflow.com/questions/18336484
复制相似问题