java - Something about Singelton -


so introduced singleton pattern, , i've found lot of great uses since, there's 1 small thing bugs me it. i've noticed in every example i've seen singleton pattern,the standard getinstance() method looks this:

    private static singleton instance = null;      public static singleton getinstance() {     if ( instance == null )          instance = new singleton();     return instance; } 

the thing want know is, there point in checking if instance variable null?

would work if assigned instance variable new singleton instance straight away , return this:

    private static singleton instance = new singleton();      public static singleton getinstance() {     return instance; } 

sorry if seems waste of time of question, wanted know if there reason why first example use everywhere.

thanks time.

edit: forgot make methods static.

both valid ways of creating singleton instance. former called lazy initialization , latter called eager initialization

lazy initialization if cost of creation of singleton instance high. in case singleton instance created when required.

on other hand, eager initialization default thread-safe


Comments

Popular posts from this blog

Android layout hidden on keyboard show -

google app engine - 403 Forbidden POST - Flask WTForms -

c - Why would PK11_GenerateRandom() return an error -8023? -