Issue
I need a single instance of one class to be used across my whole Android application. I am using the following code to achieve this and I want to be sure that doing it like this is correct, thread-safe and doesn't have an impact on performance.
public class MyClass {
private static MyClass instance;
public static synchronized MyClass getInstance() {
MyClass myClass;
synchronized (MyClass.class) {
if (instance == null) {
instance = new MyClass();
}
myClass = instance;
}
return myClass;
}
}
Whenever I need an instance of MyClass in the application, I call:
MyClass.getInstance();
So, I want ot be sure I'm not doing something wrong here, that this approach won't cause any problems down the line of development and if there are any better alternatives.
Solution
I think you don't need a second synchronized
inside getInstance
method and also you need to make MyClass
constructor to be private.
public class Singleton {
private static Singleton INSTANCE = null;
// other instance variables can be here
private Singleton() {};
public static synchronized Singleton getInstance() {
if (INSTANCE == null) {
INSTANCE = new Singleton();
}
return INSTANCE;
}
}
Answered By - logancodemaker
Answer Checked By - Candace Johnson (JavaFixing Volunteer)