java.util.concurrent API provides a class called as Lock, which would basically serialize the control in order to access the critical resource. It gives method such as park() and unpark().
We can do similar things if we can use synchronized keyword and using wait() and notify() notifyAll() methods.
I am wondering which one of these is better in practice and why?
If you’re simply locking an object, I’d prefer to use
synchronizedExample:
You have to explicitly do
try{} finally{}everywhere.Whereas with synchronized, it’s super clear and impossible to get wrong:
That said,
Locks may be more useful for more complicated things where you can’t acquire and release in such a clean manner. I would honestly prefer to avoid using bareLocks in the first place, and just go with a more sophisticated concurrency control such as aCyclicBarrieror aLinkedBlockingQueue, if they meet your needs.I’ve never had a reason to use
wait()ornotify()but there may be some good ones.