I read the available threads on the subject of Java object finalization and the reluctance of using it, still I am wondering if it's not the the best method to manage the lifetime of a DB connection for example.
The 2 threads in question:
The bottom line of those threads are that it is not recommended to use finalize for the 2 following reasons(those are the main ones that convinced me):
- Finalize is not guaranteed to be called
- Finalize() impose a performance penalty on creation and collection of objects. See Brian Goetz article here: http://www.ibm.com/developerworks/java/library/j-jtp01274.html
However, on the first thread there is a quote that seems to be key for me: "finalize should only be used for cleanup of (usually non-Java) resources". A DB connection is a resource and it seems it should be released using finalize like follows:
public class DBManager {
/**
* The connection to the database
*/
private Connection mConnection;
public void initialize() throws Exception{
// Driver
Class.forName("org.h2.Driver");
mConnection = DriverManager.getConnection("jdbc:h2:mem:test", "sa", "");
....
}
@Override
protected void finalize() throws Throwable {
// TODO Auto-generated method stub
super.finalize();
try {
// Closing the connection
mConnection.close();
} catch (Exception e) {
// TODO: handle exception
}
}
}
Now you could argue that I should have a close method in this class that would be invoked at the end of my application, this means figuring out where is the shutdown of my application, and that could vary between if it is a standalone application or run within a container. The Finalize() does give this flexibility that you don't care to close the connection. In my case I run under Spring and I don't even know where is that shutdown handler(i don't consider myself a Spring expert at all).
Another potential argument which i reject i why do i care cleaning up state if it's to handle the application shutdown use case. The answer to that is i think that it's unprofessional to not clean state, secondly profile and leak tool will report those leak which will never lead to a clear leak report and that for every application or it test that uses my object.
Is the DB connection use case above a good fit for finalize? If not how exactly such object should be managed?