2

I am trying to write a Singleton Lazy Loading Pattern. Here is the class:

public class IMDBLookup {

    private static class LazyLoad {
        private static final IMDBLookup IMDB_LOOKUP;

        static {
            IMDB_LOOKUP = new IMDBLookup();
        }
    }

    public static IMDBLookup getInstance() {
        return IMDBLookup.LazyLoad.IMDB_LOOKUP;
    }
}

I am wondering whether or not I am doing it in a right way?

Thanks in advance.

4 Answers 4

2

I prefer to use enum for simplicity.

public enum IMDBLookup {
    INSTANCE;
    // add fields and methods here.
}
Sign up to request clarification or add additional context in comments.

Comments

1

That is correct. You may want to simplify the inner (holder) class as private static final IMDBLookup IMDB_LOOKUP = new IMDBLookup(); for brevity (to get rid of the static initializer block.)

Comments

1
public class IMDBLookup {

    private IMDBLookup(){
        // without this I do not get why is it a singleton
        // anyone could create instances of your class by the thousands
    }

    private static class LazyLoad {
        private static final IMDBLookup IMDB_LOOKUP;

        static {
            IMDB_LOOKUP = new IMDBLookup();
        }
    }

    public static IMDBLookup getInstance() {
        return IMDBLookup.LazyLoad.IMDB_LOOKUP;
    }
}

and you should probably use an enum (not completely sure I do this right)

public class IMDBLookup {

    private IMDBLookup(){
    }

    private static enum LazyLoad {
        IMDB_LOOKUP_INSTANCE;
        private static final IMDB_LOOKUP = new IMDBLookup();
    }

    public static IMDBLookup getInstance() {
        return LazyLoad.IMDB_LOOKUP_INSTANCE.IMDB_LOOKUP;
    }
}

Comments

0

The advice you to think about clone & serialize

import java.io.Serializable;

public class DBConnectionInner implements Cloneable, Serializable {

    private static final long serialVersionUID = 1173438078175185035L;

    @Override
    protected Object clone() throws CloneNotSupportedException {
        return new CloneNotSupportedException("CLONE NOT SUPPORT FOR SINGTELTON");
    }

    protected Object readResolve() {
        return getInstance();
    }

    private DBConnectionInner() {}

    static DBConnectionInner getInstance() {
        System.out.println("DBConnectionInner getInstance");
        return LazyInit.instance;
    }

    public static class LazyInit {
        private static final DBConnectionInner instance = new DBConnectionInner();
    }

}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.