Saturday, August 31, 2013

Initialization-on-demand holder idiom


See Singleton Pattern here...
 
package me.dhanoop.singleton;

/**
 *
 * @author dhanoopbhaskar
 */
public class Singleton {

    private static class HelperHolder {

        public static Helper helper = new Helper();
    }

    public static Helper getHelper() {
        return HelperHolder.helper;
    }

    public static void main(String[] args) {

        Runnable runnable = new Runnable() {

            @Override
            public void run() {
                Singleton.getHelper();
            }
        };

        new Thread(runnable).start();
        new Thread(runnable).start();
        new Thread(runnable).start();
    }
}

Here as the helper object is static, an alternative is used - initialization-on-demand holder idiom. This is based on the fact that inner classes are not loaded until they are referenced.

0 comments:

Post a Comment

Contact Form

Name

Email *

Message *

The Insane Techie - Android App

Launched an android app for the blog on 07th June 2016. Get it from google play store... Tips for using the app Use in landscape mo...