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.