0

I have come across the following example code that implements a Room-database as a singleton:

public abstract class StudentDatabase extends RoomDatabase {
    public abstract StudentDao studentDao();

    private static StudentDatabase instance;

    public static StudentDatabase getInstance(final Context context) {
        if (instance == null) {
            synchronized (StudentDatabase .class) {
                if (instance == null) {
                    instance = Room.databaseBuilder(
                            context.getApplicationContext(),
                            StudentDatabase .class,
                            "student_data.db"
                    ).build();
                }
            }
        }
        return instance;
    }

Personally, I would have implemented this using:

public abstract class StudentDatabase extends RoomDatabase {
    public abstract StudentDao studentDao();

    private static StudentDatabase instance;

    private StudentDatabase() {};

    public static synchronized StudentDatabase getInstance (final Context context) {
      if (instance == null) {
        instance = Room.databaseBuilder(
                        context.getApplicationContext(),
                        StudentDatabase .class,
                        "student_data.db"
                    ).build();
      }
      instance;
    }
}

Can somebody explain to me if there is a substantial difference to these two implementations?

By the way, the private constructor was not used in the first example. I don't really know why, I always thought we have to use it in a singleton. Apart from that, I don't understand why we need the second if (instance == null).

Luk
  • 809
  • 9
  • 15

0 Answers0