The extension withLock
works on Lock
instances like ReentrantLock
, whereas synchronized
may be used with any object.
val lock = ReentrantLock()
fun syncWithLockTest(): Int = lock.withLock { 123 }
val anyLock = Any()
fun syncWithArbitraryObjTest(): Int = synchronized(anyLock) { 123 }
Note that synchronized
is a function in Kotlin which returns a value. This makes it more powerful than Java’s synchronized keyword.
Technically it doesn’t make a difference on which object you lock, as long as you use the same object for all relevant code blocks that need be synchronized with each other and don’t expose it publicly.