Thursday 23 June 2011

Lock - java.util.concurrent.locks


java.util.concurrent.locks
Interface - Lock

All Known Implementing Classes:
ReentrantLock, ReentrantReadWriteLock.ReadLock, ReentrantReadWriteLock.WriteLock .






The java.util.concurrent.locks package has a standard Lock interface. The ReentrantLock implementation duplicates the functionality of the synchronized keyword but also provides additional functionality such as obtaining information about the state of the lock, non-blocking tryLock(), and interruptible
locking
While the scoping mechanism for synchronized  methods and statements makes it much easier to program with monitor locks, and helps avoid many common programming errors involving locks, there are occasions where you need to work with locks in a more flexible way. For example, some algorithms for traversing concurrently accessed data structures require the use of "hand-over-hand" or "chain locking": you acquire the lock of node A, then node B, then release A and acquire C, then release B and acquire D and so on. Implementations of the Lock interface enable the use of such techniques by allowing a lock to be acquired and released in different scopes, and allowing multiple locks to be acquired and released in any order.

Example of using an explicit ReentrantLock instance:


import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 *
 * @author DurgaPrasad
 *
 */
public class ReentrantLockDemo {
    int counter=0;
   private final Lock lock = new ReentrantLock();
    public void getData(){
        lock.lock();
        try{
           
        }
        finally{
            lock.unlock();
        }
       
    }
}



The java.util.concurrent.locks package also containsa ReadWriteLock interface (and ReentrantReadWriteLock implementation) which is defined by a pair of locks forreading and writing, typically allowing multiple concurrent readers but only one writer. Example of using an explicit ReentrantReadWriteLock to allow multiple concurrent readers:.

public class Statistic {
private final ReadWriteLock lock = new ReentrantReadWriteLock();
private int value;
public void increment() {
lock.writeLock().lock();
try {
value++;
} finally {
lock.writeLock().unlock();
}
}
public int current() {
lock.readLock().lock();
try {
return value;
} finally {
lock.readLock().unlock();
}
}
}



Cheers !! :-)

No comments:

Post a Comment