Reputation: 247
I am using connection pooling in java. Just want to make sure i am using it correctly.
so, here is my mongoconnection class with getDatabase method.
public class MongoConnection {
private static MongoConnection mongoConnection = null;
public static MongoConnection getInstance() {
if (mongoConnection == null) {
mongoConnection = new MongoConnection();
}
return mongoConnection;
}
private MongoClient mongoClient = null;
private MongoDatabase mongoDatabase = null;
private MongoConnection() {
mongoClient = new MongoClient("localhost");
mongoDatabase = mongoClient.getDatabase("test");
}
public MongoDatabase getDatabase() {
return mongoDatabase;
}
}
and here is code snippet that uses that.
public void insertCustomer(document){
MongoCollection<Document> collection =
MongoConnection.getInstance().getDatabase().getCollection("customers");
collection.insertOne(document);
}
inserCustomer method get called multiple times.
thats all.
Upvotes: 1
Views: 5807
Reputation: 6077
Old question with only one answer which doesn't correct OP code.
This means that I am, probably, wrong, but I think that the example code provided by OP will result in all threads using the same MongoDatabase
object with the same underlying connection. I.e. threads will wait in the queue until the connection will be released by the previous thread.
I am doing it like this:
//Don't hold MongoDatabase
//private MongoDatabase mongoDatabase = null;
public MongoDatabase getDatabase() {
// every time return new instance of MongoDatabase
return mongoClient.getDatabase("test");
}
Upvotes: 0
Reputation: 255
According to the MongoDB Java driver documentation, database connection pooling is magically handled by the Mongo object.
You should use a single Mongo object(As you did), so it will do pooling for you. However, if you do use multiple objects, you need to call .close() explicitly.
so in your case one object is created and we reuse it and that object maintains the one connection to the Mongo server.
You can create one Mongo Java instance and it will maintain an internal pool of connections (default size of 10) and it's hidden and you don't need to worry about it. For more have a look..http://www.mongodb.org/display/DOCS/Java+Driver+Concurrency
Actually i'm running it in production now and there have been no issues.
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
Upvotes: 3