Right way to access Java Singleton private members

浪子不回头ぞ 提交于 2020-01-04 09:14:22

问题


If you have a Java Singleton that looks like this:

public class MySingleton {

private static MySingleton instance;

private int member;

public static MySingleton getInstance(){
    if(instance==null){
        instance = new MySingleton();
    }
    return instance;
}

private MySingleton(){
    //empty private constructor
}

public int getMemberA(){
    return member;
}

public int getMemberB(){
    return instance.member;
}

}

...is there a difference between getMemberA and getMemberB? That is, is there a difference between accessing the member with instance.xxx and just xxx?

Note: I am aware of the pros and cons of using the Singleton pattern!


回答1:


Yes, there's a difference.

Your singleton implementation isn't currently threadsafe, which means it's possible to call getMemberB() on an instance other than the one referred to by instance, at which point you'll get a different result.

If your implementation were thread-safe (so genuinely only one instance could ever be created) then they'd be equivalent, and the simpler form would be much preferred.




回答2:


No functional difference, but I find getMemberA() easier on the eye.

Note that your singleton isn't thread-safe. Two threads calling getInstance() concurrently could result in the creation of two objects. If this happens, the singleton contract is broken, and all bets are off.




回答3:


No difference in behavior, however, I'd rather use 'return member' or even 'return this.member' as this looks more intuitively.

Thread-safety is a completely different topic and this simple singleton does not meet any thread-safe singleton requirements.




回答4:


Your implementation of Singleton pattern uses lazy load technique. But it is not thread safe. We can use the synchronized keyword to make getInstance() method thread safe, but it hurts performance. It's better that we make double-check on private singleton member.

public class MySingleton {

    private volatile static MySingleton instance;

    public static MySingleton getInstance(){
        if (instance == null) {
            synchronized (MySingleton.class) {
                if (instance == null) {
                    instance = new MySingleton();
                }
            }
        }
        return instance;
    }

    private MySingleton(){
        //empty private constructor
    }
}


来源:https://stackoverflow.com/questions/10638088/right-way-to-access-java-singleton-private-members

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!