Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);
    }
}
like image 711
Sid Avatar asked Dec 08 '25 08:12

Sid


1 Answers

From the docs:

The MongoClient instance represents a pool of connections to the database; you will only need one instance of class MongoClient even with multiple threads.

And from the previous versions' quick start guides:

The MongoClient class is designed to be thread safe and shared among threads. Typically you create only 1 instance for a given database cluster and use it across your application.`

So, MongoClient.getDb(..) should not have any problem among threads

like image 54
ialex Avatar answered Dec 09 '25 22:12

ialex