10

I'm in the middle of upgrading from java driver 2.12.3 to 3.3.0. Curiously it seems that the collection pool is suddenly "acting up".

My set up is as follows:

The Connection is established in the main thread:

mongoClient = new MongoClient(new MongoClientURI("mongodb://localhost:27017"));
mongoClient.setWriteConcern(new WriteConcern(0, 10)); // deprecated, replace soon
database = mongoClient.getDatabase("Example");
// java.util.logging.Logger.getLogger("org.mongodb.driver").setLevel(Level.SEVERE);

It's used in hundreds of threads:

org.bson.Document oldDoc = DBInteractions.readOneFromDb("articles");

using functions like this:

static synchronized Document readOneFromDb(String col) {
    return database.getCollection(col).find().limit(1).sort(new Document().append("count", 1)).first();
}

And for every DB interaction I get such a warning:

Sep 26, 2016 2:33:19 PM com.mongodb.diagnostics.logging.JULLogger log
INFORMATION: Closed connection [connectionId{localValue:42, serverValue:248}] to localhost:27017 because the pool has been closed.

It looks as if the connection pool is closed after just one interaction. But why? very puzzled Anyone an idea?

1
  • 2
    No real answer, but a hint: you should have the MongoClient as the shared object which you only open up once and keep through lifetime. The MongoDatabase object is not thread-safe and should not be shared.
    – mtj
    Sep 27, 2016 at 5:35

2 Answers 2

6

https://api.mongodb.com/java/3.1/com/mongodb/MongoClientOptions.html

Look at the link. There are several method that can probably help you. Look into the timeout related methods for connection and connection pool.


EDIT: added the correct answer (it was in the comments below)

MongoClientOptions options = new MongoClientOptions.Builder().socketKeepAlive(true).build(); 
MongoClient client = new MongoClient("host", options);
4
  • 1
    That 's what I did all afternoon, and the reason why I ask here. ;) Drawing a blank on more ideas. Sep 26, 2016 at 17:25
  • 1
    see if this helps ' MongoClientOptions options = new MongoClientOptions.Builder().socketKeepAlive(true).build(); } and pass this options to MongoClient client = new MongoClient("host", options);' Sep 26, 2016 at 20:24
  • 1
    great :) happy to help. Sep 27, 2016 at 15:46
  • where do you add this? Apr 6, 2020 at 5:16
4
MongoClientOptions options = new MongoClientOptions.Builder().socketKeepAlive(true).build();

socketKeepAlive is now Deprecated.
It now defaults to true and disabling it is not recommended.

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.