elamas
elamas

Reputation: 221

How/where/when do I must call to MongoClient close?

I am developing a web application in java and I have a doubt about closing MongoClient.

Seeing this http://docs.mongodb.org/ecosystem/tutorial/getting-started-with-java-driver/#getting-started-with-java-driver

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. See the concurrency doc page for more information. The MongoClient class is designed to be thread safe and shared among threads. Typically you create only 1 instance for a given database cluster and use it across your application. If for some reason you decide to create many MongoClient instances, note that: all resource usage limits (max connections, etc) apply per MongoClient instance to dispose of an instance, make sure you call MongoClient.close() to clean up resources

and this http://docs.mongodb.org/ecosystem/drivers/java-concurrency/#java-driver-concurrency

The Java MongoDB driver is thread safe. If you are using in a web serving environment, for example, you should create a single MongoClient instance, and you can use it in every request. The MongoClient object maintains an internal pool of connections to the database (default maximum pool size of 100). For every request to the DB (find, insert, etc) the Java thread will obtain a connection from the pool, execute the operation, and release the connection. This means the connection (socket) used may be different each time.

It seems that I must have an only instance of MongoClient. My doubt is: How/where/when do I must call to MongoClient close?

Thanks

Upvotes: 3

Views: 5332

Answers (1)

Florian Schaetz
Florian Schaetz

Reputation: 10652

The API doc says:

"closes the underlying connector, which in turn closes all open connections. Once called, this Mongo instance can no longer be used. "

So, I would assume, that you only close it when you never want to open a MongoDB connection again (during this runtime). In other words, only at the end of the lifecycle of the application that uses this client instance.

Upvotes: 6

Related Questions