Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When does MongoDB Java Driver makes connection?

I am using latest Java Driver (2.11.1) for MongoDB. MongoDB Java API essentially is

  • One instance of MongoClient class (with internal connection pool)
  • getDB() for getting DB object
  • getCollection() for getting DBCollection object

1) When does a connection to db established? Is it when getDB() is called or getCollection() is called?

2) Is it better to call getDB() once or everytime you need? (does it matter? - MongoClient keeps DB object cached?)

3) Is it better to reuse single DBCollection object by multi threads or call getCollection() from multi-threads? (Is DBCollection cached?)

like image 250
shicky Avatar asked Jun 06 '13 04:06

shicky


1 Answers

The MongoClient class manages a lazy loaded connection pool from your client application to a MongoDB cluster. You can initialize MongoClient with a specific number of connections per host as well as the number of threads which wait for a connection. Since MongoClient manages both the number of connections and thread concurrency, you'll want to use one instance of the class per virtual machine. Both of DB and DBCollection perform their operations though the MongoClient's connection pool, so there's no need to cache them for that reason. There's no limit to the number of DB or DBCollection objects you instantiate. However, since these classes are thread safe and can be set with specific read preferences & write concerns, you can use a single instance of DB or DBCollection class to perform multiple operations.

like image 147
Bryan Reinero Avatar answered Oct 12 '22 02:10

Bryan Reinero