简体   繁体   English

为什么 Room 数据库初始化会同步?

[英]Why is a Room database initialisation synchronized?

While initialising the database using an abstract class in Rooms, the instance creation is generally done using synchronized .在 Rooms 中使用抽象 class 初始化数据库时,通常使用synchronized完成实例创建。 Why is this?为什么是这样?

return INSTANCE ?: synchronized(this) {
     val instance = Room.databaseBuilder(
     context.applicationContext,
     DatabaseClass::class.java,
          "database_name",
      )
     .fallbackToDestructiveMigration()
     .build()

This is to control different threads accessing the database at once, to prevent multiple instances being created.这是为了控制一次访问数据库的不同线程,以防止创建多个实例。 If you didn't synchronise here, then two different threads could both create a new instance of the database, whereas the singleton pattern is supposed to facilitate a single shared instance across the lifecycle of your program.如果您没有在此处同步,那么两个不同的线程都可以创建数据库的新实例,而 singleton 模式应该在程序的整个生命周期中促进单个共享实例。

However the example you've linked in your question generally isn't enough and you should use something like double-check locking.但是,您在问题中链接的示例通常还不够,您应该使用诸如双重检查锁定之类的东西。 So this might be better:所以这可能会更好:

return INSTANCE ?: synchronized(this) {

    INSTANCE ?: buildDatabase().also {

        INSTANCE = it
    }
}

As a side note, this isn't necessary.作为旁注,这不是必需的。 You could have no synchronisation and no shared instances.您可能没有同步,也没有共享实例。 However it is recommended for the database to be a singleton due to expensive initialisation cost, so this is one example of a pattern to use.然而,由于昂贵的初始化成本,建议数据库为 singleton,因此这是使用模式的一个示例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM