Java lazy initialization singleton instance pattern.

public class App {

    private volatile static App instance;

    private App() {}

    public static App getInstance() {
        if (instance == null) {
            synchronized (App.class) {
                if (instance == null) {
                    System.out.println("Thread " + Thread.currentThread().getId() + " is instantiating");
                    instance = new App();
                }
            }
        }
        return instance;
    }

    public static void main(String[] args) {
        for(int i = 0; i < 1000; i++) {
            new Thread(App::getInstance).start();
        }
    }
}
TOPâ–˛
Post tagged with: java