https://kotlinlang.org logo
Title
m

Marcin Wisniowski

01/28/2019, 6:37 PM
Hello, could someone tell me what is the difference between these two ways of synchronization and why would I use one over the other? I noticed it's impossible to call suspending functions inside a synchronized block but it's fine with the other way, why is that?
h

hudsonb

01/28/2019, 6:42 PM
They aren't the same, the first locks by calling
lock()
and
unlock()
on
lock
. The second holds a monitor on the
lock
object.
m

Marcin Wisniowski

01/28/2019, 6:47 PM
So what is the functional difference? Both seem to achieve the same thing?
g

ghedeon

01/28/2019, 6:52 PM
same functionality. From documentation:
Memory semantic of the Mutex is similar to synchronized block on JVM
m

Marcin Wisniowski

01/28/2019, 6:55 PM
Thank you. But then why suspending function cannot be called inside a synchronized block and can inside a
withLock
?
g

ghedeon

01/28/2019, 6:57 PM
Because
Mutex.withLock()
is suspend itself
1
m

Marcin Wisniowski

01/28/2019, 7:01 PM
Mystery solved. Thank you.
😉 1