Singleton lazy vs eager instantiation

前端 未结 5 1472
暗喜
暗喜 2020-12-07 18:51

If a singleton is implemented as follows,

class Singleton {
    private static Singleton instance = new Singleton();

    public static Singleton getInstance         


        
5条回答
  •  無奈伤痛
    2020-12-07 19:40

    For the reasons you mention, this is just a more complicated way of doing much the same as

    enum Singleton {
        INSTANCE;
    }
    

    Using lazy initialisation is only useful if you are concerned that the class could be initilised but you don't want to load the singleton at that point. For most situations this is over kill.

    Note: Just referencing the class does not initialise the class.

    e.g. Say you have a badly written class which cannot be initilised until some condition is set. In this case n must be non-zero.

    public class Main {
        public static void main(String ... args) {
            Class c= LazyLoaded.class;
            System.out.println(c);
        }
    
        static class LazyLoaded {
            static int n = 0;
            static {
                System.out.println("Inverse "+1000/n);
            }
        }
    }
    

    prints

    class Main$LazyLoaded
    

提交回复
热议问题