简体   繁体   中英

Right way to access Java Singleton private members

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!

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.

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.

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.

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
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM