Java Lock - java.util.concurrent.locks.Lock Real Time Example - Java @ Desk

Sunday, December 9, 2018

Java Lock - java.util.concurrent.locks.Lock Real Time Example

Java Lock Real Time Example

Lock in Java has been introduced in JDK 1.5 to enable synchronize mechanism. They are similar to synchronized blocks with additional features. Lock is an interface in Java and there are different implementations of Lock

1) ReentrantLock - It applies lock to a block of code in a method or block of code in different methods too. Unlike synchronized block that is applied to a whole method or a block of code within a method, Locks can be applied to blocks of code within 1 method or more than 1 method. Lock applied in one method can be unlocked in another method too.
2) ReentrantReadWriteLock - This implementation is used to perform locking when there are multiple readers and writers on a single source.

Lock interface has below important methods
1) lock() - This method acquires a lock on a resource. If a lock is not available then a thread waits indefinitely until the block is released.
2) unlock() - This method unlock the locked instance and allow another threads in waiting state to acquire a lock.

Good practice is to call unlock() method always in a finally block, otherwise in case of an exception after lock() method execution, it will remain in an infinite lock and cause deadlock situation.

Here is a sample implementation of the Lock Interface
LockThread.java - This is a thread which locks and unlocks the Lock instance created by client class. This implementation waits for infinite since it is using the lock() method. In the next implementation we will see lock implementation with time out.
package com.learning.locks;

import java.util.concurrent.locks.Lock;

public class LockThread implements Runnable {

    private Lock lock;

    private int count;

    private int time;

    public void run() {
        lock.lock();
        System.out.println("Thread " + this.count + " got locked");
        try {
            Thread.sleep(time);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        lock.unlock();
        System.out.println("Thread " + this.count + " got unlocked");
    }

    public Lock getLock() {
        return lock;
    }

    public void setLock(Lock lock) {
        this.lock = lock;
    }

    public int getCount() {
        return count;
    }

    public void setCount(int count) {
        this.count = count;
    }

    public int getTime() {
        return time;
    }

    public void setTime(int time) {
        this.time = time;
    }
}


LockClient.java - 3 Threads are created that takes different times to complete processing. The thread that acquires a lock is on random basis.
package com.learning.locks;

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

public class LockClient {

    public static void main(String args[]) {
        Lock lock = new ReentrantLock();
        int lockCount = 0;

        LockThread lockThreadOne = new LockThread();
        lockThreadOne.setLock(lock);
        lockThreadOne.setCount(++lockCount);
        lockThreadOne.setTime(10000);

        LockThread lockThreadTwo = new LockThread();
        lockThreadTwo.setLock(lock);
        lockThreadTwo.setCount(++lockCount);
        lockThreadTwo.setTime(4000);

        LockThread lockThreadThree = new LockThread();
        lockThreadThree.setLock(lock);
        lockThreadThree.setCount(++lockCount);
        lockThreadThree.setTime(1000);

        new Thread(lockThreadTwo).start();
        new Thread(lockThreadOne).start();

        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        new Thread(lockThreadThree).start();
        System.out.println("All the locks initialized");

    }
}


Output -
Thread 2 got locked
All the locks initialized
Thread 1 got locked
Thread 2 got unlocked
Thread 1 got unlocked
Thread 3 got locked
Thread 3 got unlocked






No comments:

Post a Comment