How to make sure that there is just one instance of class in JVM?

后端 未结 9 1527
离开以前
离开以前 2021-02-01 05:48

I am developing a design pattern, and I want to make sure that here is just one instance of a class in Java Virtual Machine, to funnel all requests for some resource through a s

9条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-02-01 06:25

    I prefer lazy singleton class, which overrides readResolve method.

    For Serializable and Externalizable classes, the readResolve method allows a class to replace/resolve the object read from the stream before it is returned to the caller. By implementing the readResolve method, a class can directly control the types and instances of its own instances being deserialized.

    Lazy singleton using /Initialization-on-demand_holder_idiom:

    public final class  LazySingleton {
        private LazySingleton() {}
        public static LazySingleton getInstance() {
            return LazyHolder.INSTANCE;
        }
        private static class LazyHolder {
            private static final LazySingleton INSTANCE = new LazySingleton();
        }
        private Object readResolve()  {
            return LazyHolder.INSTANCE;
        }
    }
    

    Key notes:

    1. final keyword prohibits extension of this class by sub-classing
    2. private constructor prohibits direct object creation with new operator in caller classes
    3. readResolve prohibits creation of multiple instances of class during object de-serialization

提交回复
热议问题