0

I'm developing an application in Java that connects with mongoDB with the mongoDB java driver. First of all I made mongoDB connection class in analogy with JDBC. It means that in one query app created new connection and after closed it. And in every query I create new MongoClient. And after close it. But not a long time ago in Mongo documectation I read that

The MongoClient instance actually represents a pool of connections to the database; you will only need one instance of class MongoClient even with multiple threads.

MongoClient.close() to clean up resources

I'm working with servlets. That is why I have multiple threads (in every thread I create new MongoClient).

Who can explain me should I change my code or there is no big difference between this ways?

Community
  • 1
  • 1
Adey
  • 1,846
  • 1
  • 10
  • 18
  • 1
    MongoClient is thread safe and internally manages it’s own connection pool. Best practice is to create an instance of it and reuse it. We should close it when the application is shut down, that makes ServletContextListener implementation best choice to initialize and destroy it. Refer here for eexample code: https://www.journaldev.com/4011/mongodb-java-servlet-web-application-example-tutorial – Shubham Kadlag May 07 '18 at 12:23
  • @Shubham Kadlag, thank you for example! – Adey May 07 '18 at 12:25

1 Answers1

1

The doc clearly says that the Mongo Client is threadsafe and actually is a pool of connections.

You should create only one Mongo Client and reuse in your servlets.

The thread pool initialization is rather an intensive operation so you should not create them multiple times.

Mạnh Quyết Nguyễn
  • 17,677
  • 1
  • 23
  • 51
  • Thank you for answer. Ok, but should I close something in the end of thread working? Every time app will create db and collection: mongoClient.getDatabase(databaseName); and database.getCollection(collectionName); – Adey May 07 '18 at 13:30
  • These operators are lazy, and it will create if none exists only. To close the mongo client, you should override `ServletContextListener. contextDestroyed()` – Mạnh Quyết Nguyễn May 07 '18 at 13:36