Saturday, August 31, 2013

Eager initialization

See Singleton Pattern here...

If the program will always need an instance, or if the cost of creating the instance is not too large in terms of time/resources, the programmer can switch to eager initialization, which always creates an instance.
package me.dhanoop.singleton;

 * @author dhanoopbhaskar
public class Singleton {

    private static final Helper helper = new Helper();

    public static Helper getHelper() {
        return helper;

    public static void main(String[] args) {

        Runnable runnable = new Runnable() {

            public void run() {

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

Created Helper Object

  • The instance is not constructed until the class is used.
  • There is no need of synchronization, which means all the threads will see the same instance even without expensive locking mechanism.
  • The final keyword means that the instance cannot be redefined, ensuring that one (and only one) instance ever exists.


Post a Comment

Contact Form


Email *

Message *