-1

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.

Nik
  • 1
  • 3

1 Answers1

0

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;
    }
}
logancodemaker
  • 582
  • 3
  • 14
  • Second `synchronized` functions as a lock for the time the class instance is being created. I was not quite sure if whole method synchronization is enough and therefore used it. Also, should I add `volatile` property to the `INSTANCE` variable or is that pointless? – Nik Sep 19 '22 at 18:31
  • pointless, the first `synchronized` is enough – logancodemaker Sep 19 '22 at 19:01