0

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:

  1. When is the finalize() method called in Java?
  2. Why would you ever implement finalize()?

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):

  1. Finalize is not guaranteed to be called
  2. 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?

Community
  • 1
  • 1
isaac.hazan
  • 3,772
  • 6
  • 46
  • 76
  • what is *unprofessional* is using `Class.forName()` and not actually using a real database connection pool that handles all this for you. –  Feb 10 '14 at 16:47
  • stackoverflow isn't for discussion, it is for questions and this is just a rant in disguise of a *question*. –  Feb 10 '14 at 16:51
  • The content of this post is not on using a database connection pool nor was it the intent to treat about this. And i didn't ask for an opinion on this. As for the discussion itself, i am asking a real question that a developer might face in course of developing a DB connection. I provided code exactly to not keep the discussion just at the theoretical level but to draw from it good developer practices which is exactly one of the purposes of stackoverflow. By reacting like this you are killing the discussion and prevent other to participate in a constructive discussion. – isaac.hazan Feb 10 '14 at 16:57
  • this website is **NOT** a forum, it isn't for *discussion*, *discussion* is strictly off topic and always has been, there is no question here ... read the FAQ. You already have the answer, **don't use finalize() for anything!** –  Feb 10 '14 at 17:07
  • Also this question is marked with `spring` tag, but i see no `spring problem` here. If you are working with spring bean, it has good finalizing methods(`DisposableBean` for example). – msangel Feb 10 '14 at 18:43
  • 2
    Based on the OP's own comments, I have to concur with the close vote, since he's effectively agreeing that it's off-topic by emphasizing that it's intended as a discussion of best practices. Stack Overflow is a Q&A resource for specific questions about coding with definite answers, not a discussion forum. Discussions about design concepts are more appropriate for programmers.stackexchange.com. Please read this for more information: http://meta.stackexchange.com/a/82990/228805 – Adi Inbar Feb 10 '14 at 21:20
  • Thx for the link, i didn't know the nuance. However going over that link, i am still thinking it is more stackoverflow than stack exchange for the following quotes: "if you're sitting in front of your IDE, ask it on Stack Overflow. If you're standing in front of a whiteboard, ask it on Programmers" , also from the list of topics for stackoverflow: "a specific programming problem" , this is exactly what it is and not a design pattern or sofware methodology in which case i would agree it belongs more to StackExchange. Anyway i'll keep that in mind. – isaac.hazan Feb 11 '14 at 02:57
  • This question was answered **years** ago when `JDBC` was created, you dispose of a connection when you are done with it, you don't rely on something else to do it for you. **It is a design pattern the [Dispose Pattern](http://en.wikipedia.org/wiki/Dispose_pattern) just because you don't know that doesn't make this on topic!. **That is why like I said, Use a proper connection pooling mechanism if you don't know what you are doing!** –  Feb 11 '14 at 15:04

1 Answers1

1

Answer

Use a well tested correct ConnectionPool implementation and let it do its job if you don't know the proper way to handle resource management, this is a solved problem!

Java is not C++

The finalize method isn't guaranteed to ever be called - EVER!

finalize() should be considered to not actually do anything, because it isn't guaranteed that it will ever be called during an application's lifecycle.

If you can't be convinced by the fact that a method is not guaranteed to ever be called, is a good reason to not rely on it cleaning up resources and thus creating a non-deterministic resource leak, I don't know what will!

Community
  • 1
  • 1
  • Can you articulate the cases where it wouldn't be called. It seems these cases are related to circular reference. There has to be in the JVM a list of deterministic cases in which it will happen and for which it was designed, i am asking what the designers of JVM thought when designing it and if my use case would fit it. – isaac.hazan Feb 10 '14 at 17:00
  • it won't fit, because it might not ever get called, this is very well documented on the internet, a modericum of searching will reveal dozens of articles on why this method is for all practical purposes deprecated. –  Feb 10 '14 at 17:06