Is using Locks (java.util.concurrent.locks.Lock
) instead of keyword synchronized
+ method wait()
and method notify()
totally the same?
Can I thread-safely program using locks (explicit locks) rather than implicit locks (synchronized
)?
As of know I have always been using implicit locks. I am aware of the advantages given by the Lock
interface implementation like methods: isLocked()
, getLockQueueLength()
, getHoldCount()
, etc... however still the old school way (wait()
and notify()
) would have other limits other than not having those methods?
I am also aware of the possibility of constructing a lock with a (boolean fairness) parameter which allows lack of starvation.
Yes, absolutely you can write thread-safe program using java.util.concurrent.locks.Lock
. If you see any implementation of java.util.concurrent.locks.Lock
like ReentrantLock
internal implementation uses old synchronized
blocks.
Lock implementations provide more extensive locking operations than can be obtained using synchronized methods and statements. They allow more flexible structuring, may have quite different properties, and may support multiple associated Condition objects.
Adding to my difference the synchronized
keyword has naturally built in language support. This can mean the JIT can optimise synchronised blocks
in ways it cannot with Locks
. e.g. it can combine synchronized blocks
.synchronized is best for a small number of threads accessing a lock and Lock
may be best for a high number of threads accessing the same locks . Also synchronized
block makes no guarantees about the sequence in which threads waiting to entering it are granted access.
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