An experienced programmer new to Java looking for your wisdom:
If there is no way to guarantee that any particular chunk code executes as an object goes out of scope, then what other approaches exist that will offer the same functions? (it seems that finalization is clearly not intended for this)
A classic example is the idiom of locking a lock:
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 disapproving if some code were executed, if you had not explicitly called it. But I believe that the ability to enforce any code that will be executed at the end of an object’s life is a very powerful feature to ensure that your classes are used reasonably by client code. Thanks
java
user1659313
source share