Darshan Patel
Darshan Patel

Reputation: 2899

MongoDB java driver connection management

I have recently started learning MongoDB in Java and I found that I don't have to worry about closing connection per query just like we did for Mysql and other sql database.

I want to know, how well MongoDB java driver manage connection for every request? Did they take care it in java driver?

Upvotes: 2

Views: 1665

Answers (1)

Mark Bramnik
Mark Bramnik

Reputation: 42491

I don't really understand what you mean by "designing a Java Driver". Mongo comes with its own java driver. I assume, you don't mean creating an alternative driver, but merely want to use an existing driver with MongoDB.

In this case, you don't really need to manage connections from within your application. Mongo Java Driver maintains a connection pool internally, so when you make, say, insert operation, it will fetch a connection from its internal pool, issue an insert action to MongoDB and close the connection.

According to Mongo Documentation, the Driver is thread safe. You should add some code in certain cases when you work with replica set and slaveOk option, but I assume you're talking about more basic cases.

You should create a single object of MongoClient object and use it in your application even when it's multi-threaded. The only thing you need to do is call

mongoClient.close() 

just before you dispose the instance of the driver.

A tutorial of what can be done with the Mongo java driver can be found here

Hope, this helps

Upvotes: 2

Related Questions