Skip to content

Commit

Permalink
AsyncSingletonProvider: double-checked locking pattern (#2078)
Browse files Browse the repository at this point in the history
* AsyncSingletonProvider: doubled-checked locking pattern

* Update AsyncSingletonProvider.kt

* Format AsyncSingletonProvider.kt

* Fmt AsyncSingletonProvider.kt

---------

Co-authored-by: Gino Miceli <228050+gino-m@users.noreply.github.com>
  • Loading branch information
hoc081098 and gino-m authored Nov 29, 2023
1 parent f914481 commit c10c2af
Showing 1 changed file with 2 additions and 7 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ import kotlinx.coroutines.sync.withLock

/** Base class for providers for singletons which need to be initialized asynchronously. */
open class AsyncSingletonProvider<T>(private val providerFunction: suspend () -> T) {
private var instance: T? = null
@Volatile private var instance: T? = null
private val mutex = Mutex()

/**
Expand All @@ -30,10 +30,5 @@ open class AsyncSingletonProvider<T>(private val providerFunction: suspend () ->
* until the singleton is created and returned.
*/
suspend fun get(): T =
mutex.withLock {
if (instance == null) {
instance = providerFunction()
}
return instance!!
}
instance ?: mutex.withLock { instance ?: providerFunction().also { instance = it } }
}

0 comments on commit c10c2af

Please sign in to comment.