Wednesday, December 16, 2009

Best practice: ReentrantReadWriteLock

Best practice: ReentrantReadWriteLock

Excellent lock and unlock mechanism to make thread safe particular code using ReentrantReadWriteLock. For instance, specified thread made lock and due to some exception, thread did not reach to unlock code and came out of run() method. We may think that presence of Thread does not exist now, the lock whatever acquired by the thread has to be release after a while. Reality is not that, no way we can get/reclaim the lock in ReentrantReadWriteLock. It would be nice to have such an API to fire and release weakReferenced Threads lock and facilitate the Reader/Writer to acquire the lock.



In JDK1.6, It is our code job to release the lock whenever it compeleted or else some exception happened while doing process.



Best practice to keep unlock code always in finally block, to make sure all locks release before coming out of the thread. If you run, following code, this program will not be terminated and T2 wait for ever.




import java.util.concurrent.locks.ReentrantReadWriteLock;

public class ReentrantTest {
private static final ReentrantReadWriteLock rwl = new ReentrantReadWriteLock(true);
private static  ReentrantReadWriteLock.ReadLock readlock=rwl.readLock();
private static  ReentrantReadWriteLock.WriteLock writelock=rwl.writeLock();

public static void main(String[] args) throws Exception{

new Thread()
{
@Override
public void run() {
System.out.println("entering into lock for T1");
readlock.lock();
System.out.println("Lock Acquire for T1");
//readlock.unlock();
}
}.start();

new Thread()
{
@Override
public void run() {
try{sleep(100);}catch(Exception e){}
System.out.println("entering into lock for T2");

writelock.lock();

System.out.println("Lock Acquire for T1");
}
}.start();

// Thread.sleep(10000);
}
}



Best practice would be, place unlock as used below


writelock.lock();
try
{
//business goes here
}finally
{
writelock.unlock();
}

readlock.lock();
try {
//do read operation here
} finally {
readlock.unlock();
}

Reactions:

0 comments:

Post a Comment

Recent Posts

Unix Commands | List all My Posts

Texts

This blog intended to share the knowledge and contribute to JAVA Community such a way that by providing samples and pointing right documents/webpages. We try to give our knowledege level best and no guarantee can be claimed on truth. Copyright and Terms of Policy refer blogspot.com

Share

Twitter Delicious Facebook Digg Stumbleupon Favorites More