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?
I would define it a third way
public class MyService {
final static MySingleton singleton = MySingleton.getInstance();
public void myMethod1() {
// code ...
}
public void myMethod2() {
// code...
}
public void myMethod3() {
// code...
}
}
In all cases there is no difference in thread-safety