[MS-1030] Implement thread-safe access to Realm instance using Mutex#1229
Conversation
| private val mutex = Mutex() | ||
|
|
||
| private fun getRealm(): Realm { | ||
| private suspend fun getRealm(): Realm = mutex.withLock { |
There was a problem hiding this comment.
Is this required for every realm call? Once it is initialised and migrated, this could slow down the reading significantly, no?
There was a problem hiding this comment.
Yeah, can't we move this inside the if?
There was a problem hiding this comment.
Pull Request Overview
Adds coroutine-based synchronization to ensure the Realm instance is only initialized once across concurrent calls.
- Imports
MutexandwithLockfromkotlinx.coroutines.sync - Introduces a
Mutexproperty and convertsgetRealm()into asuspendfunction usingwithLock - Removes the non-locked return path to guarantee thread-safe access
Comments suppressed due to low confidence (3)
infra/enrolment-records/realm-store/src/main/java/com/simprints/infra/enrolment/records/realm/store/RealmWrapperImpl.kt:39
- [nitpick] Consider renaming
mutexto something more descriptive likerealmInitMutexto clarify its purpose.
private val mutex = Mutex()
infra/enrolment-records/realm-store/src/main/java/com/simprints/infra/enrolment/records/realm/store/RealmWrapperImpl.kt:41
- Add a KDoc comment explaining that this function is
suspendand uses aMutexto ensure the Realm instance is initialized only once and is safe for concurrent calls.
private suspend fun getRealm(): Realm = mutex.withLock {
infra/enrolment-records/realm-store/src/main/java/com/simprints/infra/enrolment/records/realm/store/RealmWrapperImpl.kt:41
- Consider adding a unit or integration test that launches multiple coroutines calling
getRealm()simultaneously to verify only one Realm instance is created and no race conditions occur.
private suspend fun getRealm(): Realm = mutex.withLock {
| private suspend fun getRealm(): Realm = mutex.withLock { | ||
| if (!this::realm.isInitialized) { | ||
| config = createAndSaveRealmConfig() | ||
| realm = createRealm() | ||
| } | ||
| return realm | ||
| realm |
There was a problem hiding this comment.
To avoid locking on every call, you could do a fast-path check before acquiring the mutex, e.g., if (::realm.isInitialized) return realm outside the lock, then synchronize only the initialization block.
a520889 to
0e89770
Compare
0e89770 to
62beff3
Compare
|



JIRA ticket
Will be released in: 2025.2.0
Root cause analysis (for bugfixes only)
First known affected version: long time ago
Notable changes
Added a Mutex to synchronize access to getRealm() and ensure that only one thread initializes the Realm instance. This prevents the crash and guarantees that the schema is applied only once.
Testing guidance
Additional work checklist