Tuesday 30 January 2018

Multithreading | Deadlock using CountDownLatch

According to the functionality of Countdown Latch, await() method blocks the execution of the current thread until the count reaches zero. Here CountDownLatch initialized as 10, and there are 4 threads which are used to reduce the count of CountDownLatch and await () method will wait infinitely to get 0 as CountDownLatch value. 4 threads are able to reduce the count by 4 from 10. So count will never reach zero and execution of main thread keep waiting for infinite time.

Line below the await() method will wait infinitely to decrease the countdown value.

package com.threads.countdown;
import java.util.concurrent.CountDownLatch;

class StopLatchedThread extends Thread {

    private final CountDownLatch stopLatch;
    private int threadId;

    public StopLatchedThread(CountDownLatch stopLatch, int i) {
        this.stopLatch = stopLatch;
        this.threadId = i;
    }

    @Override
    public void run() {
        try {
            System.out.println("inside the run method of " + threadId + " thread");
        } finally {
            System.out.println("Count down by " + threadId + " thread");
            stopLatch.countDown();
        }
    }
}

/**
 * @author rajesh.kumar2
 */
public class DeadLockCoundDownLatch extends Thread {

    public static void main(String[] args) throws InterruptedException {
        performParallelTask();
    }

    public static void performParallelTask() throws InterruptedException {
        CountDownLatch cdl = new CountDownLatch(10);
        for (int i = 0; i < 4; i++) {
            Thread t = new StopLatchedThread(cdl, i);
            t.start();
        }
       
        System.out.println("Before await method");
        System.out.println("Waiting for the further execution of Main thread...");
        cdl.await();

        /** This statement will not execute because cdl.await() method will wait till Count will reduced to 0. */
        System.out.println("After await method");
    }
}


No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...