Locks in Java

A lock in Java is used with threads. It is an thread synchronization mechanism and is very similar to the synchronized keyword which is used in Java.

Compared to synchroized blocks, it is more sophisticated to use.From Java 5 the package java.util.concurrent.locks contains several lock implementations

Let’s see an example.

public class LockExample{

  private Lock lock = new Lock();
  private int cnt = 0;

  public int increaseCnt(){
    lock.lock(); //line 5
    int newCnt = ++cnt; //line 6
    lock.unlock();//line 7
    return newCnt;
  }
}

If you see the above example, the class instance variable cnt has default value 0. In the method at line 5, the lock method is called on the lock instance which will lock the object.

Other threads who try to call the lock method after that would be blocked till it is unlocked.

Then at line 6, the cnt is incremented.

At line 7, the lock object is unlocked and other threads who were blocked on the same object at line 5 would be unblocked try to get the lock.

Below is the sample implementation of the Lock class.

public class Lock{

  private boolean isLocked = false;

  public synchronized void lock()
  throws InterruptedException{
    while(isLocked){ //Line 5
      wait(); //Line 6
    }
    isLocked = true;//Lne 8
  }

  public synchronized void unlock(){
    isLocked = false;//Line 11
    notify();//Line 12
  }
}

If you see, internally it is implemented using the synchronized method and uses wait-notify.

Let us consider 3 threads using the same lock class object.

The first thread calls the synchronized lock method. At line 5 it gets the value of isLocked as false as it is set default. So it skips the while block and doesn’t call wait() method.

Then at Line 8, it sets the value of isLocked as true and exits the lock method thereby releasing the class object.

Now thread 2, enters the synchronized lock method, At line 5, it gets value of isLocked as true so it goes into wait state by entering the while loop and calling wait() method.

Then thread 1, calls the unlock method, and sets the value as false at line 11 and calls notify method at line 12 to notify other threads.

So thread 2 which was in wait state now moves ahead.