Singleton Design Pattern


references

double-checked locking

public class MySingleton {

    private volatile Some some = null;               // volatile

    public Some getSome() {
        if (some == null) {                          // check 1
            synchronized (this) {
                if (some == null) {                  // check 2
                    some = new MySingleton();
                }
            }
        }
        return some;
    }
}

initialization-on-demand holder idiom

public class MySingleton {

    private static class InstanceHolder {
        private static final MySingleton INSTANCE = new MySingleton(); // final
    }

    public static MySingleton getInstance() {
        return InstanceHolder.INSTANCE;
    }

    private MySingleton() {
        super();
    }
}
Advertisements

One comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s