Android Room数据库:数据库属性的线程安全使用

Android Room数据库:数据库属性的线程安全使用,android,android-room,kotlin-coroutines,Android,Android Room,Kotlin Coroutines,为了支持使用NTP对时间敏感数据进行时间同步,我在RoomDatabase中添加了Volatile属性,所有更新操作都可以从该属性请求“时间戳”。但我想知道,在使用暂停功能和事务的房间时,这是否是线程安全的?也不太确定它是否必须被标记为易失性,因为每次访问都应该产生一个新的java.time.Clock 例如: abstract class AppDatabase : RoomDatabase() { abstract val chatRepository: ChatRepositor

为了支持使用NTP对时间敏感数据进行时间同步,我在
RoomDatabase
中添加了
Volatile
属性,所有更新操作都可以从该属性请求“时间戳”。但我想知道,在使用暂停功能和事务的房间时,这是否是线程安全的?也不太确定它是否必须被标记为易失性,因为每次访问都应该产生一个新的
java.time.Clock

例如:

abstract class AppDatabase : RoomDatabase() {

    abstract val chatRepository: ChatRepository
    abstract val taskRepository: TaskRepository
    abstract val userSampleRepository: UserRepository

    companion object {
        private const val DB_NAME = "example_database"

        @Volatile
        internal var clock: Clock = Clock.systemDefaultZone()
            private set

        ...
        @JvmStatic
        fun withClock(clock: Clock) {
            synchronized(this) {
                this.clock = clock
            }
        }
    }
}
使用时:

abstract class TaskRepository
...
    private suspend fun updateAll(tasks: List<TaskEntity>) = updateAllInternal(
        tasks.map {
            TaskEntity.Builder()
                .copyOf(it)
                .withUpdatedAt(OffsetDateTime.now(AppDatabase.clock))
                .create()
        }
    )
...
}
@Test
fun whenRequestingDefaultClock_shouldCreateUpdatedTimestamp() {
    val firstTimestamp = Instant.now(AppDatabase.clock)
    sleep(1) // Adding 1ms delay to ensure Clock is not fixed and returns a different timestamp
    val secondTimestamp = Instant.now(AppDatabase.clock)

    assertThat(firstTimestamp).isLessThan(secondTimestamp)
}

@Test
fun whenSwitchingToFixedClock_shouldUseSameTimestamp() {
    val instant = Instant.now()
    val clock = Clock.fixed(instant, Clock.systemDefaultZone().zone)
    AppDatabase.withClock(clock)
    val firstTimestamp = Instant.now(AppDatabase.clock)
    sleep(1) // Adding 1ms delay to ensure Clock is fixed and returns a fixed timestamp
    val secondTimestamp = Instant.now(AppDatabase.clock)

    assertThat(firstTimestamp).isEqualTo(secondTimestamp)
}