sovon
sovon

Reputation: 907

make mongoClient object/any object available across the application

Hello i am working with mongodb java driver. In their documentation, they mentioned that,

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, I want to make this object available for every user. how can i do this?

Upvotes: 0

Views: 202

Answers (1)

sovon
sovon

Reputation: 907

The best way to do this is to use Singleton design pattern. This is the code-

public class MongoDBManager {
    public MongoClient mongoClient = null;
    String host = "127.0.0.1";
    static MongoDBManager mongo=new MongoDBManager();
    private MongoDBManager() {
        try {
            mongoClient = new MongoClient( host , 27017);
            } catch (UnknownHostException e) {
            System.err.println("Connection errors");
            e.printStackTrace();
        }
    }

    public static MongoDBManager getInstance(){
        return mongo;
    }
}

Call only MongoDBManager.getInstance() whenever you need connection. only one object will be used.

Upvotes: 1

Related Questions