Mongo opens too many connections Mongo opens too many connections mongodb mongodb

Mongo opens too many connections


You are creating an instance of the Mongo class for each individual operation. That won't work since each instance will create and hold at least one connection (but by default, 10) and those connections will only be removed if the Java GC cleans up your Mongo instance or when you invoke close().

The problem is that in both cases you're creating them faster than they are being closed even using a single thread. This will exhaust the maximum amount of connections in a hurry. The right fix is to keep one Mongo instance around using the singleton pattern (Mongo.Holder provides functionality for this, try Mongo.Holder.connect(..)). A quick "fix" is to increase the file descriptor limit on your machine so the maximum amount of connections is considerably higher but obviously you eventually might hit the same limit. You can check your current max using (in shell) :

db.serverStatus().connections

TL;DR : Treat a Mongo instance as a singleton and make them as long-lived as possible and you're golden. Implementing a MongoFactory with a static method getInstance() that returns a lazily created instance will do the trick just fine. Good luck.


You're making a new MongoClient everytime you come through your method.

I had this problem as well, but i solved it making a checkConnection function:

private static DBCollection checkConnection(String collection) throws UnknownHostException{    if(db == null){        db = (new MongoClient(host, port)).getDB(database);    }    return db.getCollection(collection);}

On top where you instantiate your variables, have this:

private static DB db = null;private static String database = "<Your database>";private static String host = "localhost"; //<--- usually localhostprivate static int port = 27017; //<---- usually 27017, but you can change it.

Then when you make a method, have it like this:

 public <whatever> someFunction() throws UnknownHostException{    DBCollection dbCollection = checkConnection("triples"); //<--- can be "triples"                                                    //or whatever collection you want     <REST OF YOUR FUNCTION HERE USING THE AMAZING COLLECTION }

This approach has a few advantage:

- Code reusability, you won't have to write the same thing at every method- Readability, which programmer doesn't understand this:   DBCollection dbCollection = checkConnection("triples");  - ONLY ONE CONNECTION WHICH YOU RE-USE (this doesn't affect data not being synced)

Hope I helped