A Java service that connects to MongoDB in production, but opened connection count is too much. It affects on MongoDb performance, so I have come up with a solution that provides only one MongoClient
instance so which will reduce the connections.
Here is my code, is it a good way to provide a singleton object from 3rd party library?
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
public class MongoClientFactory {
private static volatile MongoClient instance = null;
private MongoClientFactory() {}
public static MongoClient getInstance(String connectionString) {
if (instance == null) {
synchronized(MongoClientFactory.class) {
if (instance == null) {
instance = MongoClients.create(connectionString);
}
}
}
return instance;
}
}