Reputation: 2485
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
Upvotes: 0
Views: 55
Reputation: 20061
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.
Upvotes: 1
Reputation: 6233
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.
Upvotes: 1