Reentrant Lock example of a task runner

With this example we are going to demonstrate how to implement a ReentrantLock of a task runner. The ReentrantLock is a reentrant mutual exclusion Lock with the same basic behavior and semantics as the implicit monitor lock accessed using synchronized methods and statements, but with extended capabilities. The custom Class that have implemented is called TaskRunner and consists of the two methods. In short:

Let’s take a look at the code snippet that follows:

public class TaskRunner {
    private Map<Class<? extends Runnable>,  Lock> mLocks =
new HashMap<Class<? extends Runnable>,  Lock>();
    public void runTaskUniquely(Runnable r, int secondsToWait) {
  Lock lock = getLock(r.getClass());
  boolean acquired = lock.tryLock(secondsToWait, TimeUnit.SECONDS);
  if (acquired) {
try {;
} finally {
  } else {
// failure code here
    private synchronized Lock getLock(Class clazz) {
  Lock l = mLocks.get(clazz);
  if (l == null) {
l = new ReentrantLock();
mLocks.put(clazz, l);
  return l;

This was an example of how to implement a ReentrantLock of a task runner in Java.

Related Article:

Reference: Java Concurrency Part 2 – Reentrant Locks from our JCG partners at the Carfey Software blog

Exit mobile version