0

I'd need to use the MongoClient and DB objects repeatedly in a Web application:

MongoClient mongoClient = new MongoClient();
DB db = mongoClient.getDB( "test" );

Is it safe to cache and re-use these objects among different clients accessing our application?
Thanks

2 Answers 2

1

You should create this once and inject it via CDI/Guice, if you can. If you can't do that, you could use a static factory method to return the one instance of your MongoClient. MongoClient maintains a connection pool and is safe to use between different threads. If you create a new MongoClient with each request, not only is it going to be a performance hit to set up that pool and open a new connection, but you'll likely leave dangling connections unless you properly close that MongoClient at the end of the request.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks from your reply. By means of CDI sounds nice for a Java EE environment.
1

Yes. From Getting Started with Java Driver, "you will only need one instance of class MongoClient even with multiple threads".

As a side note, the Mongo Java driver is a pain to use. The dev team I'm part of is very happy with Jongo, a wrapper around the Java driver that allows queries to be written more like shell queries.

1 Comment

Thanks for sharing the link, sounds quite interesting!

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.