What is difference between ReentrantLock and Synchronization

ReentrantLock and Synchronization are the two most common ways of getting exclusive control of some block of code so that no parallel threads can access it. But both have differences and ReentrantLock is always a better choice to use. Here are primary differences between ReentrantLock and Synchronization

1. Fair Locking

ReentrantLock can guarantee fairness of the order in which threads acquire the locks. In synchronization if multiple threads are waiting for the lock, once lock is released any thread can acquire the lock. With fair locking, threads can acquire locks only in the order in which they were requested

This is unfair lock :

 Lock lock = new ReentrantLock();

This is fair lock :

 Lock lock = new ReentrantLock(true);

2. Interruptible Lock Acquisition

If a synchronized block goes into a waiting state with the hope of getting a lock, there is noway of interrupting it and getting it out of wait state.

Thread t1 = new Thread(new Runnable() {
 
			@Override
			public void run() {
				try {
					lock.lockInterruptibly();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				sharedlist.add("one");
				lock.unlock();
			}
		});
 
		Thread t2 = new Thread(new Runnable() {
 
			@Override
			public void run() {
 
				lock.lock();
				sharedlist.add("two");
				t1.interrupt();				
				lock.unlock();
 
			}
		});

In above code suppose thread t2 first acquires the lock and thread t1 is waiting but can be interrupted. Now once t1.interrupt is called, thread t1 will no lonnger wait and next lines will get executed

3. Timed Lock Acquisition

In synchronization thread can either acquire the lock or keep on waiting.There is no way to specify how lock should thread wait for the lock before proceeding ahead. Now this is possible using reentrant lock. We can acquire lock using tryLock method and specify the time thread should wait for. If lock does not get acquired within this time, thread will move on and no longer wait for the lock. If no parameters are passed, JVM will check if lock is available or not. If not available thread will not wait and will move on

try {
					lock.tryLock(4, TimeUnit.SECONDS);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

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 *