How to write a Singleton in proper manner?

后端 未结 13 1150
走了就别回头了
走了就别回头了 2020-12-23 12:03

Today in my interview one interviewer asked me to write a Singleton class. And i gave my answer as

public class Singleton {

    private static Singleton re         


        
13条回答
  •  被撕碎了的回忆
    2020-12-23 12:41

    It could be because it does not use "double-checked-locking" (as others have said) or it could also be because it is apparently possible to invoke a private constructor using reflection (if the security policy allows it).

    To invoke a constructor with no parameters pass an empty array.

    package org.example;
    
    public class Singleton {
    
        private static final Object LOCK = new Object();
        private static final Singleton SINGLETON = new Singleton();
        private static volatile boolean init = false; // 'volatile' to prevent threads from caching state locally (prevent optimizing) 
    
        private Singleton() {
            synchronized (LOCK) {
                if( init == true) {
                    throw new RuntimeException("This is a singleton class!");
                }
                init=true;
            }
        }
    
        public static Singleton obtainClassInstance() {
            return SINGLETON;
        }
    
    }
    
    
    package org.example;
    
    import java.lang.reflect.Constructor;
    import java.lang.reflect.InvocationTargetException;
    
    public class SimpleSingletonTester {
    
        /**
         * @param args
         * @throws NoSuchMethodException 
         * @throws SecurityException 
         * @throws InvocationTargetException 
         * @throws IllegalAccessException 
         * @throws InstantiationException 
         * @throws IllegalArgumentException 
         */
        public static void main(String[] args) throws SecurityException, NoSuchMethodException, 
        IllegalArgumentException, InstantiationException, IllegalAccessException, InvocationTargetException 
        {
    
            Class[] parameterTypes = {};
            Object[] initargs = {};
            Constructor constructor = Singleton.class.getDeclaredConstructor(parameterTypes);
            System.out.println( constructor.isAccessible() );
            constructor.setAccessible(true);
            System.out.println( constructor.isAccessible() );
            System.out.println( constructor.newInstance(initargs) );
            System.out.println( constructor.newInstance(initargs) );
    
        }
    
    }
    

提交回复
热议问题