【问题标题】:Can the singleton contract be broken? If yes in how many ways?单例合约可以被破坏吗?如果是,有多少种方式?
【发布时间】:2018-07-21 13:58:53
【问题描述】:

最近我出现在面试中,她/他问我一个问题 - 你的单身阶级低于单身,你必须打破单身合同,告诉我该怎么做?我想了又想,但我无法提出解决方案,因为每项检查都是为了防止违规行为 -

  1. 从主内存读取/写入的可变关键字
  2. 围绕方法和块同步
  3. 获取实例的静态方法
  4. 双重检查实例是否可用
  5. 私有构造函数

下面是代码 -

/**
 * 
 */
package com.test.singleton;

/**
 * @author 
 *
 */
public class SingletonInstance implements Cloneable{

    private String name;

    private static volatile SingletonInstance instance;

     private SingletonInstance(){

        System.out.println("constructor called");
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    static synchronized SingletonInstance getInstance(){

    if(instance == null){

        synchronized(SingletonInstance.class){
            instance = new SingletonInstance();
        }

    }
    return instance;
}

    /* (non-Javadoc)
     * @see java.lang.Object#clone()
     */
    @Override
    protected Object clone() throws CloneNotSupportedException {
        // TODO Auto-generated method stub
        return super.clone();
    }

}

请建议是否有可能以任何方式打破单例合同?

【问题讨论】:

  • 您没有具体说明“违反合同”的含义。不管怎样,这段代码是不正确的,当getInstance()被调用时它总是会抛出NPE(实际上是synchronized(null)),所以它永远不会初始化实例。
  • 您尝试克隆并返回相同的实例?我不相信你。
  • 感谢 Jim 指出这一点。更正了代码。从“违反合同”这个术语来看,我的意思是可以以任何方式创建类的两个实例,@Ernest 已经使用反射以非常好的方式回答了这一点,以及如何防止这种情况
  • @shmosel 从术语相同的实例来看,我在写问题时正在考虑实例的相同内容。现在我意识到措辞不正确。在问题中进行了更正。谢谢!!!
  • 我还是不明白为什么不能用克隆来解决这个问题。

标签: java singleton synchronized volatile cloning


【解决方案1】:

在几种情况下,您的单例类可能有多个实例。到现在为止,我心里有两点。

  1. 通过反射调用私有构造函数。
  2. 通过序列化和反序列化。

这是通过私有构造函数调用停止创建对象的方法。

private SingletonInstance(){
          if(instance != null){
                throw new OperationNotSupportedException("You can't create object of singletone class using this operation");
         }
       }

此外,您可以通过添加 readObject 和 readResolve 方法来停止通过序列化和反序列化创建单例类的多个对象,如下所示。

private void readObject(ObjectInputStream inputStream) throws ClassNotFoundException, IOException  {
    inputStream.defaultReadObject();
    instance = this;
}

private Object readResolve() {
    return instance;
}

另外,你的克隆方法应该通过异常。

  protected Object clone() throws CloneNotSupportedException {
       throw new CloneNotSupportedException("Clone not supported for this class");
    }

【讨论】:

  • 如果从单独的线程调用反射仍然可以击败您的私有构造函数。你需要同步测试null来强制volatile生效
  • 你有一个类型throw an exception
  • 这里不能使用序列化,因为SingletonInstance 没有实现Serializable 及其private 构造函数有效地阻止了可序列化的子类。
【解决方案2】:

构造函数虽然是私有的,但可以使用反射调用:

Class<SingletonInstance> klass = SingletonInstance.class;
Constructor<SingletonInstance> defaultConstructor = klass.getConstructor();

defaultConstructor.setAccessible(true);
SingletonInstance newInstance = defaultConstructor.newInstance();

这样,可以创建多个实例。

为了防止这种情况,它应该包含自己的检查,如有效 java 中所建议的那样:

private SingletonInstance(){ 
    if(instance != null)
        throw new IllegalStateException(); //or some other exception
    System.out.println("constructor called"); 
}

【讨论】:

  • 如果从单独的线程调用反射仍然可以击败您的私有构造函数。您需要同步测试null以强制volatile生效
  • @Bohemian 甚至 synchronized 在这里都无济于事,因为您可以在第一次调用 getInstance() 之前简单地创建自己的实例,而无需涉及任何并发。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-11-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多