Assuming that we have a thread safe singleton class in Java, which would be the best or better way to use it. For instance, consider that we have a Singleton class as:
public class MySingleTon { // my thread-safe code goes here } And we have a service class that uses the above singleton in the two possible ways as follows :
1:
public class MyService { MySingleton singleton; public void myMethod1() { singleton = MySingleton.getInstance(); // code ... } public void myMethod2() { singleton = MySingleton.getInstance(); // code... } public void myMethod3() { singleton = MySingleton.getInstance(); // code... } } or
2:
public class MyService { public void myMethod1() { MySingleton singleton = MySingleton.getInstance(); // code ... } public void myMethod2() { MySingleton singleton = MySingleton.getInstance(); // code... } public void myMethod3() { MySingleton singleton = MySingleton.getInstance(); // code... } } In case one the singleton is referenced via an instance variable and in case 2, the singleton is referenced as a method local variable. Considering that both the above snippets are used in multi-threaded environment, which is a better option and why?
myMethods going to change state of singleton, can they be synchronized?method1can set its own state of singleton and do some other things based on assumption that this state stays. But in the same timemethod2can try to change this state to something else. Would it be problem in your case? Would it be possible?singletonvariable. But even that case is completely safe because the threads always update it with the same object reference. Java guarantees that when a thread reads a reference variable, it will always see a value that was stored at some previous time by the program, and since there's only one value that is ever stored... You do the math.