Right way to access Java Singleton private members

java, singleton

Solution

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.

Problem

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!

Original source