Tuesday, 25 August 2015

Deadlock using CountDownLatch

Deadlock using CountDownLatch

Here CountDownLatch initialized as 10; and there are 4 threads which are used to reduce the count of CountDownLatch, and await () method will wait infinite to get 0 as CountDownLatch value.

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


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

public class TestCountDownLatch extends Thread {
       public static void main(String[] argsthrows 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();
              }
              cdl.await();
             
              // this statement will not execute because cdl.await() method will wait
              // till 0 value of CountDownLatch cdl.
              System.out.println("after await method");
       }
}

package com.threads;

import java.util.concurrent.CountDownLatch;

public class StopLatchedThread extends Thread {
       private final CountDownLatch stopLatch;
       private int threadNo;
       public StopLatchedThread(CountDownLatch stopLatchint i) {
              this.stopLatch = stopLatch;
              this.threadNo = i;
       }
      
       public void run() {
              try {
                     System.out.println("inside the run method of "+threadNo" thread");
              } finally {
                     System.out.println("count down by "+threadNo" thread");
                     stopLatch.countDown();
              }
       }
}
Output :
inside the run method of 0 thread
count down by 0 thread
inside the run method of 3 thread
count down by 3 thread
inside the run method of 2 thread
count down by 2 thread
inside the run method of 1 thread
count down by 1 thread

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...