can anyone explain how to use Reentrant Lock in java over Synchronized with some best examples

user2473958 picture user2473958 · Aug 28, 2013 · Viewed 7.7k times · Source

When I run the example class at http://javarevisited.blogspot.in/2013/03/reentrantlock-example-in-java-synchronized-difference-vs-lock.html, I'm seeing the same behavior as with synchronized.

Answer

programstinator picture programstinator · Aug 28, 2013

Here are three ways, methods, of a thread accessing a lock and one for letting go of the lock. You might want to try implementing these using the synchronized keyword. The extended capabilities and advantages of using ReentrantLock will become apparent.

public class DoorLockUsingLock {

    private int counter= 0;
    private Thread owner= null;
    private Lock l = new ReentrantLock();
    private Condition notLocked= l.newCondition();

    public void lockItDown() throws InterruptedException {
        l.lockInterruptibly();
        try {
            while ((counter> 0) && (owner!= Thread.currentThread())) {
                notLocked.await();
            }
            counter++;
            owner = Thread.currentThread();
        } finally {
            l.unlock();
        }
    }

    public void lockItDownUninterruptibly() {
        l.lock();
        try {
            while ((counter > 0) && (owner != Thread.currentThread())) {
                notLocked.awaitUninterruptibly();
            }
            counter++;
            owner= Thread.currentThread();
        } finally {
            l.unlock();
        }
    }

    public boolean tryLockItDown(long timeout, TimeUnit unit) throws InterruptedException {
        long time = unit.toNanos(timeout);
        long end = System.nanoTime() + time;
        boolean success = l.tryLock(timeout, unit);
        if (!success) {
            return false;
        }
        try {
            time = end- System.nanoTime();
            while ((counter> 0) && (owner != Thread.currentThread()) && (time > 0)) {
                notLocked.await(time, TimeUnit.NANOSECONDS);
                time = end - System.nanoTime();
            }
            if (time > 0) {
                counter++;
                owner = Thread.currentThread();
                return true;
            }
            return false;
        } finally {
            l.unlock();
        }
    }

    public void unlockIt() throws IllegalMonitorStateException {
        l.lock();
        try {
            if (counter== 0) {
                throw new IllegalMonitorStateException();
            }
            if (owner!= Thread.currentThread()) {
                throw new IllegalMonitorStateException();
            }
            counter--;
            if (counter == 0) {
                owner = null;
                notLocked.signal();
            }
        } finally {
            l.unlock();
        }
    }
}