Java – explicit and implicit locks
Using locks (Java. Util. Concurrent. Locks. Lock) instead of the keyword synchronized, is the method wait() exactly the same as the method notify()?
Can I use locks (explicit locks) instead of implicit locks (synchronization) to program thread safely?
As far as I know, I have been using implicit locks I know the advantages of the lock interface implementation, such as methods: islocked(), getlockqueuelength(), getholdcount(), etc... but the old school methods (wait() and notify()) still have other limitations, except for those methods?
I also know the possibility of constructing a lock with (Boolean fairness) parameters, which allows lack of hunger
Solution
Yes, you can definitely use Java util. concurrent. locks. Lock writes thread - safe programs If you see Java util. concurrent. locks. Any implementation of lock, like reentrantlock's internal implementation, uses the old synchronized block
Lock implementation provides a wider range of lock operations than those obtained using synchronous methods and statements They allow more flexible structures, may have completely different properties, and can support multiple associated condition objects
In addition to my differences, the synchronized keyword naturally has built-in language support This may mean that JIT can optimize synchronization blocks in a way that locks cannot For example, it can combine synchronized blocks Synchronized is best for a small number of threads accessing locks, and lock may be best for a large number of threads accessing the same lock Synchronization blocks also do not guarantee the order in which access is granted to threads waiting to enter them