-
-
Notifications
You must be signed in to change notification settings - Fork 3.1k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
PlayerUiList: guard list actions with mutex
The new implementation would throw `ConcurrentModificationExceptions` when destroying the UIs. So let’s play it safe and put the list behind a mutex. Adds a helper class `GuardedByMutex` that can be wrapped around a property to force all use-sites to acquire the lock before doing anything with the data.
- Loading branch information
1 parent
5b92de4
commit 2f32929
Showing
2 changed files
with
87 additions
and
19 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
47 changes: 47 additions & 0 deletions
47
app/src/main/java/org/schabi/newpipe/util/GuardedByMutex.kt
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,47 @@ | ||
package org.schabi.newpipe.util | ||
|
||
import kotlinx.coroutines.runBlocking | ||
import kotlinx.coroutines.sync.Mutex | ||
import kotlinx.coroutines.sync.withLock | ||
|
||
/** Guard the given data so that it can only be accessed by locking the mutex first. | ||
* | ||
* Inspired by [this blog post](https://jonnyzzz.com/blog/2017/03/01/guarded-by-lock/) | ||
* */ | ||
class GuardedByMutex<T>( | ||
private var data: T, | ||
private val lock: Mutex = Mutex(locked = false), | ||
) { | ||
|
||
/** Lock the mutex and access the data, blocking the current thread. | ||
* @param action to run with locked mutex | ||
* */ | ||
fun <Y> runWithLockSync( | ||
action: MutexData<T>.() -> Y | ||
) = | ||
runBlocking { | ||
lock.withLock { | ||
MutexData(data, { d -> data = d }).action() | ||
} | ||
} | ||
|
||
/** Lock the mutex and access the data, suspending the coroutine. | ||
* @param action to run with locked mutex | ||
* */ | ||
suspend fun <Y> runWithLock(action: MutexData<T>.() -> Y) = | ||
lock.withLock { | ||
MutexData(data, { d -> data = d }).action() | ||
} | ||
} | ||
|
||
/** The data inside a [GuardedByMutex], which can be accessed via [lockData]. | ||
* [lockData] is a `var`, so you can `set` it as well. | ||
* */ | ||
class MutexData<T>(data: T, val setFun: (T) -> Unit) { | ||
/** The data inside this [GuardedByMutex] */ | ||
var lockData: T = data | ||
set(t: T) { | ||
setFun(t) | ||
field = t | ||
} | ||
} |