Friday, May 5, 2017

Lock and ReentrantLock in Java Example

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

public class LockCounter {
    private Lock lock = new ReentrantLock();
    private static int count = 0;

    public int increment(){
        lock.lock();  //Comment this Line to see abnormal multithreading behavior
        count++;
        System.out.println("In: "+count);
        lock.unlock();  //Comment this Line to see abnormal multithreading behavior
        return count;
    }
    public int decrement(){
        lock.lock();  //Comment this Line to see abnormal multithreading behavior
        count--;
        System.out.println("De: "+count);
        lock.unlock();  //Comment this Line to see abnormal multithreading behavior
        return count;
    }
    public static void main(String[] args){
        new Thread(new Runnable(){public void run(){
            LockCounter obj = new LockCounter();
            while(true){
                obj.increment();
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            }}).start();
        new Thread(new Runnable(){public void run(){
            LockCounter obj = new LockCounter();
            while(true){
                obj.decrement();
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            }}).start();
    }
}

//Output: We have disabled Lock API. lock() and unlock() were commented here.
In: 1
De: 0
In: 1
De: 1
De: 1
In: 1
De: 1
In: 1
De: 1
In: 1
In: 0
De: 0
In: 0
De: 0
De: 0
In: 0
In: 0
De: 0
In: 0
De: 0
De: 0
In: 0
In: 1
De: 0
In: 1
De: 0
In: 1
De: 0
De: -1
In: 0
De: -1
In: 0
In: 1
De: 0
De: 0
In: 0
In: 1
De: 1
De: 1
In: 1
In: 1
De: 1

//After Implementing Lock and ReentrantLock API
//Output: We have ENABLED Lock API. lock() and unlock() were UN-Commented here.
In: 1
De: 0
In: 1
De: 0
In: 1
De: 0
In: 1
De: 0
In: 1
De: 0
In: 1
De: 0
In: 1
De: 0
In: 1
De: 0
In: 1
De: 0
In: 1
De: 0
In: 1
De: 0
In: 1
De: 0
In: 1
De: 0
In: 1
De: 0
In: 1
De: 0
In: 1
De: 0
In: 1
De: 0
In: 1
De: 0
In: 1
De: 0

No comments:

Post a Comment