Synchronization VS Locks
There are few differences between the use of synchronized block and using Lock API’s
- A synchronized block is fully contained within a method we can
have Lock API’s lock() and unlock() operation in separate
methods.
public class ThreadDemo extends Thread { Lock lock = new ReentrantLock(); public int sum(int a, int b) { //Locking in one method lock.lock(); a = 10; b = 20; return a + b; } public void show() { System.out.println(sum(10, 20)); //UnLocking in another method lock.unlock(); } }
-
A synchronized block does not support the fairness, any thread can acquire the lock ones released, no preference can be specified. We can achieve fairness within the Lock APIs by specifying the fairness property. It makes sure that longest waiting thread is given access to lock.
- A thread gets blocked if it can’t get an access to the
synchronized block. The Lock API provides tryLock() method. The thread
acquires lock only if it’s available and not held by any other
thread. This reduces blocking time of thread waiting for the lock.
if(l.tryLock()) {//perform safe operations }else{ //perform alternative operations }
- A thread which is in -waiting” for a long time(say hours) to acquire the access to synchronized block, can’t be interrupted. The Lock API provides a method lockInterruptibly() which can be used to interrupt the thread when it is waiting for the lock
PREVIOUSjava-util-Concurrency
NEXTReadWriteLock