Java MongoDB client as a singleton
Simple answer: No. Unless if your application only ever runs on 1 thread.

The easiest way to lazy initialise a singleton thread safe would be with a holder pattern. Example from wikipedia:

public class Something {
    private Something() {}

    private static class LazyHolder {
        static final Something INSTANCE = new Something();
    }

    public static Something getInstance() {
        return LazyHolder.INSTANCE;
    }
}


This is thread safe because the java class loader ensures that the INSTANCE is initialised exactly once, when the LazyHolder class is used for the first time.

Since the database you initialise isn't known at compile time in this class you cannot use this pattern. What you can do is a pattern called double-checked locking:

public final class Singleton {
    private static volatile Singleton instance = null;

    private Singleton() {}

    public static Singleton getInstance() {
        if (instance == null) {
            synchronized(Singleton.class) {
                if (instance == null) {
                    instance = new Singleton();
                }
            }
        }
        return instance;
    }
}


Important here are the synchronized(...) and volatile keywords.
The synchronised part makes sure only 1 thread can execute the construction code. And the volatile ensures that all threads always see all changes to the variable.