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 {


    r.run();


} finally {


    lock.unlock();


}

  } 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

Share and enjoy!
© 2010-2012 Examples Java Code Geeks. Licenced under a Creative Commons Attribution-ShareAlike 3.0 Unported License.
All trademarks and registered trademarks appearing on Examples Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Examples Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.