Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between Lock.withLock and synchronized in Kotlin

Tags:

Is there a difference (other than preference) between

someLock.withLock {     sharedResource.operation() } 

and

synchronized(someLock) {     sharedResource.operation() } 

in Kotlin?

like image 262
EvenLisle Avatar asked Dec 08 '17 20:12

EvenLisle


People also ask

What is the difference between synchronized and lock?

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.

What is synchronized () in Kotlin?

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.

What is synchronized block in Kotlin?

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.

What is the advantage of the new lock interface over a synchronized block in Java?

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.


1 Answers

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.

like image 104
s1m0nw1 Avatar answered Sep 17 '22 07:09

s1m0nw1