MongoClient has an internal connection pool. You can configure the maximum number of connections (default is 100). You can install it using MongoClientOptions as follows:
MongoClientOptions options = MongoClientOptions.builder() .connectionsPerHost(100) .autoConnectRetry(true) .build();
And then give these parameters to MongoClient (check it in Mongo Java API v2.11.1). Connections in the pool are kept open (opening and closing connections is usually an expensive operation) so that they can later be reused.
I would also reorganize your singleton MongoDB client using enum , for example, so as not to put synchronized in this method.
Here is a sketch of what I mean:
public enum MongoDB { INSTANCE; private static final String MONGO_DB_HOST = "some.mongohost.com"; private Mongo mongo; private DB someDB; MongoDB() { MongoClientOptions options = MongoClientOptions.builder() .connectionsPerHost(100) .autoConnectRetry(true) .readPreference(ReadPreference.secondaryPreferred()) .build(); try { mongo = new MongoClient(MONGO_DB_HOST, options); } catch (UnknownHostException e) { e.printStackTrace(); } someDB = mongo.getDB("someDB");
Then you can access your database through
MongoDB.INSTANCE.getSomeDB().getCollection("someCollection").count();
source share