Experienced programmer new to Java seeking your wisdom:
If there is no way to ensure that some particular chunk code is executed as an object goes out of scope, then what other approaches are there that would offer the same functionality? (it seems finalize is clearly not meant for that)
A classic example is the scoped lock idiom:
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 {...}
}
I can understand that in Java it would be frowned upon to have some code executed if you haven't explicitly called it. But I find being able to enforce some code to be executed at the end of an object's lifetime is a very powerful feature to ensure your classes are being used sensibly by client code. Thanks
Objects are persistent, meaning they exist in memory until you destroy them. We can break the life of an object into three phases: creation and initialization, use, and destruction.
It would live until at least the start() method finished executing, there is no guarantee about object lifetimes in Java since memory is managed by the garbage collecter and not the programmer.
You can delete an object in Java by removing the reference to it by assigning null. After that, it will be automatically deleted by the Garbage Collector.
Java uses a technique known as garbage collection to remove objects that are no longer needed. The garbage collector is Java's grim reaper. It lingers in the background, stalking objects and awaiting their demise. It finds and watches them, periodically counting references to them to see when their time has come.
Generally - if you have a need to actually close/dispose of resources then using a try{} finally{}
structure is encouraged.
// 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();
}
}
More recent incarnations of java have the AutoCloseable interface which you can use with the with
mechanism. All Closeable objects are automatically 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.
}
As of Java 7 there is the Automatic Resource Management. If your lock is under your control, then make it implement AutoCloseable
. Unfortunately, the java.util.concurrent
locks do not implement this interface. Here's a good reference to the details of that.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With