Home > Software engineering >  Singleton class in Android application using synchronized initalizer
Singleton class in Android application using synchronized initalizer

Time:09-20

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.

CodePudding user response:

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;
    }
}
  • Related