10

I am using Java driver to access mongodb. I assume the db connection pooling is internally handled by the driver.But my connection count getting increased every time I access db.

This is my serverStatus log.

"connections" : {
            "current" : 276,
            "available" : 543
    }

Do I need to explicitly close mongo connections? how should I manage connection pooling in java?

Green
  • 28,742
  • 61
  • 158
  • 247
Deepan
  • 1,559
  • 3
  • 14
  • 18
  • possible duplicate of [MongoDB Java Driver database connection pooling with Tomcat](http://stackoverflow.com/questions/4647636/mongodb-java-driver-database-connection-pooling-with-tomcat) – fyr Jan 23 '12 at 06:59

3 Answers3

21

You should use a single Mongo object, so it will do pooling for you. However, if you do use multiple objects, you do need to call .close() explicitly.

From: http://www.mongodb.org/display/DOCS/Java+Tutorial

The Mongo class is designed to be thread safe and shared among threads. Typically you create only 1 instance for a given DB cluster and use it across your app. If for some reason you decide to create many mongo intances, note that:

all resource usage limits (max connections, etc) apply per mongo instance to dispose of an instance, make sure you call mongo.close() to clean up resources

Eve Freeman
  • 32,467
  • 4
  • 86
  • 101
  • 1
    You should definitely avoid multiple clients for a single application. You want to minimize the total number of connections into a MongoDB deployment since each one requires almost 1MB of RAM in overhead meaning less available for cache. – Nic Cottrell Oct 22 '19 at 09:39
5

MongoDB, MongoDB is act as connection pool for mongoDB and it is created per application and per DB basis.

Typically you only create one MongoClient instance for a given MongoDB deployment (e.g. standalone, replica set, or a sharded cluster) and use it across your application. However, if you do create multiple instances:

All resource usage limits (e.g. max connections, etc.) apply per MongoClient instance.

Ref: http://mongodb.github.io/mongo-java-driver/3.4/driver/tutorials/connect-to-mongodb/

MongoClientOptions options = 
MongoClientOptions.builder()
            .threadsAllowedToBlockForConnectionMultiplier(prop.getThreadsAllowedToBlock())
.connectionsPerHost(pro.getConnectionsPerHost())
.connectTimeout(prop.getConnectionTimeout())
.maxWaitTime(prop.getConnectionTimeout())
.socketTimeout(1000)
.heartbeatConnectTimeout(prop.getHeartbeatConnectTimeout())
.writeConcern(WriteConcern.ACKNOWLEDGED).build();

MongoClient mongoclient = new MongoClient(seeds,credential, options); credential, options);

This is working as connection pool. We can instantiate MongoTemplate from MongoClient.

Rajeev Rathor
  • 1,830
  • 25
  • 20
2

You can set max pool size mongodb://***/?maxPoolSize=5 for detail Review this documentation https://docs.mongodb.com/manual/reference/connection-string/

Karthik
  • 317
  • 4
  • 17