6

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?)

1
  • There is a simple test in order to know: create a main() which does a simple query, with your MongoDB shut down, and see where it barfs :p
    – fge
    Jun 6, 2013 at 4:52

2 Answers 2

7

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.

0

1) connection is established when we do some operation ( find, update, remove, etc )

2) Doc says : "Typically you create only 1 instance for a given database cluster and use it across your application". So, there is no point of caching DB object, and it is also not cached in driver code

3) DBCollection and DB are thread-safe. DBCollection are cached in DBApiLayer class in the driver.

2
  • 1
    Doc says there should be one instance of MongoClient per JVM. How does this relate to caching DB or DBCollection object.
    – shicky
    Jun 6, 2013 at 18:02
  • DB object is something which is a logical representation of actual database. May be my language used is wrong, yes the details of DB has to be cached, but it is just 1 DB object per MongoClient, but many DBCollection per DB. Jun 6, 2013 at 20:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.