Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Closing MongoDB Java Connection

I am trying to design a Mongo Db connection class where I am maintaning MongoClient as static.

private static MongoClient client = null;

public static DB connectToMongo() throws Exception {
    if (null != client) {
        return client.getDB(DBNAME);
    }       
    client = new MongoClient(HOST,PORT);                
    return client.getDB(DBNAME);    
}

My whole web application uses the above method to connect to Mongo as follows:

db = MongoDBConnection.connectToMongo();
collection = db.getCollection("collectionName");

After performing DB operations I never call the close connection for MongoClient. The connection class would always return the same instance of MongoClient which is never closed.The only thing I close is cursors.

  • Is it necessary to close the MongoClient every time we query the database? Is my above design valid?
like image 305
Ecnoir Avatar asked Nov 13 '14 17:11

Ecnoir


People also ask

How do I close a MongoDB connection?

javascript, node.js, database, mongodb The MongoClient#close() method API documentation says: Close the client, which will close all underlying cached resources, including, for example, sockets and background monitoring threads.

Should I keep MongoDB connection open?

It is best practice to keep the connection open between your application and the database server.

How do I close a node connection?

To close a connection and remove it from the pool, you use the connection. destroy() method.

Can I connect MongoDB with Java?

Connecting via Java. Assuming you've resolved your dependencies and you've set up your project, you're ready to connect to MongoDB from your Java application. Since MongoDB is a document database, you might not be surprised to learn that you don't connect to it via traditional SQL/relational DB methods like JDBC.


1 Answers

You should definitely not close the MongoClient every time you query the database. The MongoClient maintains a connection pool, which is relatively expensive to set up, so you'll want to re-use the MongoClient instance across the lifetime of your web application.

A couple of other things to point out:

  • There is a race condition in the connectToMongo method. You need to synchronize access to that method to ensure that at most one instance of MongoClient is ever created.
  • If you ever re-deploy your web application without first restarting your application server, you must ensure that the MongoClient is closed when your web application is shutdown. You can do that, for example, with a ServletContextListener.
like image 98
jyemin Avatar answered Sep 27 '22 18:09

jyemin