Difference between Lock.withLock and synchronized in Kotlin

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.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)