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:

  • It creates a HashMap of a Class that extends the Runnable and a Lock.
  • It implements a method, runTaskUniquely(Runnable r, int secondsToWait) that calls a private method of the class, getLock(Class clazz).
  • The getLock(Class clazz) gets the Lock of the specified class, using the get(Object key) API method of Map. If the Class is not mapped to a Lock, then it creates a new ReentrantLock, puts it in the map and returns it.
  • The runTaskUniquely(Runnable r, int secondsToWait) method calls the getLock(Class clazz) method to get the Lock of the Class, and acquires the lock if it is free within the given waiting time, with tryLock(long time, TimeUnit unit) API method of Lock. If the lock is available this method returns immediately with the value true, and the Class uses its run() method to create a thread.
  • Finally the class releases the lock, using unlock() API method of Lock.

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

Ilias Tsagklis

Ilias is a software developer turned online entrepreneur. He is co-founder and Executive Editor at Java Code Geeks.
Notify of

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Newest Most Voted
Inline Feedbacks
View all comments
Back to top button