java Singleton - prevent multiple creation through reflection

前端 未结 6 897
无人及你
无人及你 2021-01-30 22:52

I have a singleton like this.

public class BookingFactory {

    private final static BookingFactory instance;

    static {
        instance = new BookingFactor         


        
6条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-30 23:32

    Adapted from Making the Java Singleton Reflection Proof when using Lazy Loading:

    package server;
    
    import java.lang.reflect.ReflectPermission;
    import java.security.*;
    
    
    public class JavaSingleton {
    
      private static JavaSingleton INSTANCE = null;
    
      private JavaSingleton() {
        ReflectPermission perm = new ReflectPermission("suppressAccessChecks", "");
        AccessController.checkPermission(perm); 
      }
    
    
      synchronized public static final JavaSingleton getInstance() {
        if (INSTANCE == null) {
          AccessController.doPrivileged(new PrivilegedAction() {
            public Object run() {
              INSTANCE= new JavaSingleton();
              return null;
            }
          });
        }
        return INSTANCE;
      }
    
    
    

    The constructor has a check to see if the caller has access to it. As the link explains, a policy file that permits the Singleton class itself to call the constructor will need to be created.

    Bohemian's method of throwing an exception does not prevent a client from reflectively calling the constructor before getInstance() is called. Even though it ensures that only one instance gets created, there's no guarantee that this is done by the Singleton class' getInstance() method.

    The access control check will prevent this unwanted instantiation.

    提交回复
    热议问题