1

I have a question about closing resources (AutoCloseable or not) that are static members of a Java class. In my particular situation I have a class that manages connections to a MongoDB instance using a static MongoClient instance variable. How would I ensure that this client is closed as the documentation recommends when my application terminates? I am using this class as part of the back end to a Java webapp which is run in a container (Tomcat 7). I could not override the Object's finalize() method to close the client because that is called on an instance of the class and would have no effect on static members correct? Here is my example code:

public class MyManager {
    //This needs to be closed when the application terminates
    private static MongoClient CLIENT;

    static {
        ...
        CLIENT = new MongoClient("localhost", 27017);
        ...
    }

    public static DB getSomeDB(String dbName) {
        return CLIENT.getDB(dbName);
    }

    //more factory methods
    ...

    //Would this work?
    @Override
    protected void finalize() throws Throwable {
        CLIENT.close();
    }
}

Can someone tell me how to best handle this situation and in general with resources such as a database connection or JDBC driver? Thanks!

JasonMArcher
  • 14,195
  • 22
  • 56
  • 52
mike
  • 11
  • 2
  • 2
    Check out this answer for using a shutdown hook: http://stackoverflow.com/questions/2921945/useful-example-of-a-shutdown-hook-in-java – Hobbyist Nov 29 '14 at 20:54
  • This should suit your needs, I use it in all of my server/client applications. – Hobbyist Dec 02 '14 at 21:28

1 Answers1

-2

We are using Spring and simply create a bean which calls the close() method once it's being destroyed:

@Bean(name = "mongoClient", destroyMethod = "close")
public MongoClient mongoClient() throws MongoException, UnknownHostException {
    ...
xeraa
  • 10,456
  • 3
  • 33
  • 66
  • 1
    Thanks but I am not using Spring. Can you tell me how to do this using the Java standard library? – mike Dec 02 '14 at 18:43