At API docs of Lock
interface for method tryLock()
, this code sample is pasted,
A typical usage idiom for this method would be:
Lock lock = ...; if (lock.tryLock()) { try { // manipulate protected state } finally { lock.unlock(); } } else { // perform alternative actions }
My question is , does this use case not existed before Java 5 or folks used to implement it via some other techniques?
I am not able to comprehend the need to execute perform alternative actions based on lock availability.
Can somebody please explain real use cases for this?
I am sure this technique is not a straight forward replacement of synchronized
to write deadlock free code.
One straight-forward use case is a thread processing a batch of elements, occasionally trying to commit the elements that have been processed. If acquiring the lock fails, the elements will be committed in the next successful attempt or at the final, mandatory commit.
Another example can be found within the JRE itself, ForkJoinTask.helpExpungeStaleExceptions()
is a method for performing a task that can be done by an arbitrary thread, but only one at a time, so only the one thread successfully acquiring the lock will perform it, all others will return, as the unavailability of the lock implies that there is already a thread performing the task.
It is possible to implement a similar feature before Java 5, if you separate the intrinsic locking feature, which doesn’t support being optional, from the locking logic, that can be represented as an ordinary object state. This answer provides an example.
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