Is there a difference (other than preference) between
someLock.withLock { sharedResource.operation() }
and
synchronized(someLock) { sharedResource.operation() }
in Kotlin?
Major difference between lock and synchronized: with locks, you can release and acquire the locks in any order. with synchronized, you can release the locks only in the order it was acquired.
A thread that enters a synchronized method obtains a lock (an object being locked is the instance of the containing class) and no other thread can enter the method until the lock is released. Kotlin offers the same functionality with the @Synchronized annotation.
Sometimes, holding a lock for the entire duration of a function call is too expensive and Java offers to run parts of the code under a lock, again with the synchronized keyword. To achieve the same behavior, Kotlin offers the synchronized function.
The major advantage of lock interfaces on multi-threaded and concurrent programming is they provide two separate lock for reading and writing which enables you to write high-performance data structure like ConcurrentHashMap and conditional blocking. A thread can take a lock only once.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With