两个条件检查单例模式的INSTANCE是否为null

时间:2018-10-18 18:26:45

标签: java android android-room

我正在学习Android体系结构组件。在Room中定义数据库时,两次检查了RoomDatabase类的实例是否为null。下面是代码。我不明白为什么需要两次检查相同的情况。

    @Database(entities = {Word.class}, version = 1)
    public abstract class WordRoomDatabase extends RoomDatabase {

       public abstract WordDao wordDao();

       private static volatile WordRoomDatabase INSTANCE;

       static WordRoomDatabase getDatabase(final Context context) {
            if (INSTANCE == null) {
                synchronized (WordRoomDatabase.class) {
                    if (INSTANCE == null) {
                        INSTANCE =  Room.databaseBuilder(context.getApplicationContext(),                    
                                WordRoomDatabase.class, "word_database")
                                .build();
                    }
                }
            }
            return INSTANCE;
        }
    }

0 个答案:

没有答案