private val lock = SynchronizedObject()
...
public actual override fun use(instance: T) {
synchronized(lock) {
doSomething(instance)
}
}
What happens if
doSomething
is a suspendable function?
Is this a use-case that I can handle somehow?
j
Jeff Lockhart
08/21/2023, 2:40 PM
You could use
reentrantLock()
instead:
Copy code
val lock = reentrantLock()
lock.lock()
doSuspendSomething()
lock.unlock()
Jeff Lockhart
08/21/2023, 2:43 PM
SynchronizedObject()
also supports manually calling
lock()
and
unlock()
too.
e
Edoardo Luppi
08/21/2023, 3:41 PM
Thanks @Jeff Lockhart, I was mainly wondering if a suspension point in the middle of a lock could cause some kind of undefined behavior
j
Jeff Lockhart
08/21/2023, 3:47 PM
There's nothing wrong with locking and unlocking the lock from different threads. A thread that is waiting on the lock will block until it's unlocked, so you'd just want to be sure there's not a lot of threads blocking waiting on the lock, otherwise it may make sense to use a suspending, rather than blocking, alternative, like