https://kotlinlang.org logo
Title
f

feroz_baig

07/27/2017, 11:04 AM
Why
Mutex
is slower than
ReentrantLock
?
e

elizarov

07/27/2017, 1:14 PM
@feroz_baig It depends on how you compare them.
f

feroz_baig

07/27/2017, 1:18 PM
I ran the sample code of running 1000 coroutines each performing 1000 tasks on a shared resource. We want synchronizing to be done. Context is CommonPool. With
Mutex
locks, it took around 4 sec. And with
ReentrantLock
it took 1 sec. Why such behaviour?
e

elizarov

07/27/2017, 1:23 PM
ReentrantLock is more efficient and it is not abortable in the same sense that Mutex is cancellable.
For short CPU-consuming action you’ll almost always get better performance with ReentrantLock, because it is what RL is optimized for
Mutex is designed for the cases, where critical section has suspension points inside and thus can run for longer time.
Moreover, Mutex is always fair. If you run ReentrantLock in fair mode (pass true to its constructor) it should erase some of its advantage
f

feroz_baig

07/27/2017, 1:28 PM
I will check this out! Thanks!