Is this a valid way to ensure only a single instance of an object exists in Java?

java, singleton

Solution

You have to set your public member mongoSingleton as private and to hide the default constructor

so

private static Mongo mongoSingleton = null;

private Mongo() {

}

the class Mongo implementation

public class Mongo {
    private static volatile Mongo instance;
    private Mongo() {
        ...
    }

    public static Mongo getInstance() {
        if (instance == null) {
            synchronized (Mongo.class) {
                if (instance == null) { // yes double check
                    instance = new Mongo();
                }
            }
        }

        return instance;
    }
}

usage

Mongo.getInstance();

Problem

I have been getting some strange errors with Mongodb, and in Mongodb, you are supposed to mainatin the `Mongo` singleton. I just wanted to make sure that this is infact valid. ``` public class DBManager { public static Mongo mongoSingleton = null; public static synchronized void getMongo(){ if(mongoSingleton == null){ mongoSingleton = new Mongo(); } return mongoSingleton; } } ``` Thanks!

Original source

Related problems