Closing a MongoDB Java Connection

I am trying to create a Mongo Db connection class where I support 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 entire web application uses the above method to connect to Mongo as follows:

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

After performing operations with the database, I never call a close connection for MongoClient. The join class always returned the same MongoClient instance that never closes. The only thing I close is the cursors.

  • Do we need to close MongoClient every time we query the database? Is my project higher?
+5
source share
1 answer

Be sure not to close MongoClient every time you query the database. MongoClient maintains a connection pool, which is relatively expensive to configure, so you'll want to reuse an instance of MongoClient throughout the life of your web application.

A few other things to indicate:

  • The connectToMongo method has a race condition. You need to synchronize access to this method to ensure that no more than one instance of MongoClient is created.
  • If you have ever redeployed your web application without restarting the application server, you must ensure that MongoClient is closed when your web application shuts down. You can do this, for example, using ServletContextListener.
+15
source

Source: https://habr.com/ru/post/1206820/


All Articles