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