jeudi 16 novembre 2017

mongodb connection thread safety

I am using the following code based on some tutorials to connect to the mongo database.

I have some doubts regarding the design:

  1. Is it okay to call the MongoConnection.getDB() function from multiple threads simultaneously?
  2. If not, should I make it synchronized?
  3. If the design has issues, what kind of unwanted impact could it have?

I am new to mongodb so my question may sound a bit naive.

public class MongoConnection {

    private static MongoClient mongoClient = null;

    private static String IP = "mongodb://user:pwd@localhost:27017/?authSource=demodb&authMechanism=SCRAM-SHA-1";
    private static String DATABASE = "demodb";

    static {
        mongoClient = new MongoClient(new MongoClientURI(IP));
    }

    private MongoConnection() {

    }

    public static DB getDB() {
        return mongoClient.getDB(DATABASE);
    }
}

Aucun commentaire:

Enregistrer un commentaire