Tim
Tim

Reputation: 279

Mongodb Java API opens too many connections in servlet

As I understand you only need one instance of MongoClient per applications so I've extended HttpServlet with this method for convenience:

DB getDB(String dbName) throws Exception {
    MongoClient m = (MongoClient)getServletContext().getAttribute("mongo");
    if(m == null) {
        m = new MongoClient();
        getServletContext().setAttribute("mongo",m);
    }
    return m.getDB(dbName);
}

When I run this code it works just fine and I connect and do what work I need to, but it seems to continually open new connections to mongodb everytime I run this particular Servlet:

Sat Jan 26 21:31:42 [initandlisten] connection accepted from 127.0.0.1:46860 #1 (1 connection now open)
Sat Jan 26 21:31:53 [initandlisten] connection accepted from 127.0.0.1:46861 #2 (2 connections now open)
Sat Jan 26 21:32:00 [initandlisten] connection accepted from 127.0.0.1:46863 #3 (3 connections now open)

In the page I am doing this:

DB db = getDB("foo");
col = db.getCollection("bar");

and then running a simple query. Can anyone explain why I'm getting so many new connections? Also I've seen this Mongo.Holder class. Is this the preferred way to do what I am doing?

Thanks!

Upvotes: 0

Views: 1765

Answers (2)

jyemin
jyemin

Reputation: 3813

The default maximum size of the connection pool increased from 10 to 100 in MongoClientOptions, which is mentioned in the detailed Javadoc: http://api.mongodb.org/java/current/com/mongodb/MongoClientOptions.html#getConnectionsPerHost().

If you are using MongoOptions, the default is still 10.

Upvotes: 0

lobster1234
lobster1234

Reputation: 7779

MongoDB Java driver implements a connection pool, and by default maintains 10 connections. The pool is managed internally by the driver. You should not see more than 10 connections going out to Mongo server from your servlet container. If you wish to change these default settings, check out MongoOptions.

Upvotes: 1

Related Questions