Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use case for Lock.tryLock()

At API docs of Lockinterface 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 synchronizedto write deadlock free code.

like image 264
Sabir Khan Avatar asked Jan 22 '17 06:01

Sabir Khan


1 Answers

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.

like image 68
Holger Avatar answered Oct 03 '22 09:10

Holger