Implement a Reentrant Lock in Java

can you buy prometrium over the counter by · March 5, 2018

Let’s try to implement our own custom Lock. For sake of simplicity we will not implement interruptible, non-interruptible, and timed forms of the lock

/*
 * For sake of simplicity - assume custom lock interface having only three
 * methods.
 */
interface CustomLock {
 public void lock();
 public boolean tryLock();
 public void unlock();
}
/*lock method implementation of CustomLock interface*/
public synchronized void lock() {
 /*
  * Acquires the lock if it is not held by another thread and set lock
  * hold count to 1.
  */
 if (lockHoldCount == 0) {
  lockHoldCount++;
  threadId = Thread.currentThread().getId();
 }
 /*
  * If current thread already holds lock then hold count is increased by
  * 1 - Chain locking.
  */
 else if (lockHoldCount > 0
   && threadId == Thread.currentThread().getId()) {
  lockHoldCount++;
 }
 // If the lock is held by another thread then the current
 // thread waits for another thread to release lock.
 else {
  try {
   wait();
   lockHoldCount++;
   threadId = Thread.currentThread().getId();
  } catch (InterruptedException e) {
   e.printStackTrace();
  }
 }
}
/*unlock method is executed to release lock*/
public synchronized void unlock() {
 /*
  * If current thread is not holding the lock, if unlock is called it
  * throws IllegalMonitorStateException.
  */
 if (lockHoldCount == 0)
  throw new IllegalMonitorStateException();
 /* If lock is held, decrement lock hold count by 1 */
 lockHoldCount--;
 
 /*
  * If lockHoldCount is 0, lock is released and waiting thread is
  * notified.
  */
 if (lockHoldCount == 0)
  notify();
}
/*tryLock method returns true if lock is available and calls lock() interanlly*/
public synchronized boolean tryLock() {
 /*
  * Acquires the lock if it is not held by another thread and // returns
  * true
  */
 if (lockHoldCount == 0) {
  lock();
  return true;
 }
 // If lock is held by another thread then method return false.
 else
  return false;
}

Uday Ogra

Connect with me at http://facebook.com/tendulkarogra and lets have some healthy discussion :)

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *