MongoDB Java Driver database connection pooling with Tomcat

16,142

We've been using the Java drivers via the CFMongoDB project and we use it as you describe, but in a ColdFusion application rather then in Java. Same idea though: one object is created and we reuse it and that object maintains the one connection to the Mongo server.

You can create one Mongo Java instance and it will maintain an internal pool of connections (default size of 10) - to you it's hidden and you don't need to worry about it. The Mongo Java docs recommend this:

http://www.mongodb.org/display/DOCS/Java+Driver+Concurrency

We have it running in production now and there have been no issues. Multiple web request threads use the same Mongo instance and Mongo is quick enough to deal with this using it's internal pool (we're doing logging so it can write very fast!).

It is worth remembering to call close() on any instances that you are finished with - this will stop connections getting used up on the Mongo server over time:

http://api.mongodb.org/java/2.5-pre-/com/mongodb/Mongo.html#close()

So in summary, don't worry about configuring Tomcat.

Hope that helps!

Share:
16,142

Related videos on Youtube

anon
Author by

anon

Updated on May 15, 2022

Comments

  • anon
    anon almost 2 years

    According to the MongoDB Java driver documentation, database connection pooling is magically handled by the Mongo object.

    Does this mean it is safe to create an instance of a singleton object which connects to the MongoDB database in a servlet that will run when Tomcat starts and not worry about configuring database connection pooling in Tomcat via the context.xml?

    Is this the right way to think about it? Am I misunderstanding some basic concept of Tomcat / database connection pooling in general?

    • DevilCode
      DevilCode about 8 years
      Thanks anaon I have the same question but you have phrased it much better than I did.