Thursday, September 8, 2016

JAVA MULTITHREADING: Thread synchronization using Countdown Latches

Using CountDownLatch is very useful in situation where certain threads need to complete before something else can be started.
This has no timeout feature like ExecuterService's awaitTermination() method.

The latch.await() method will pass back control to the main() method only when the countDown has reached ZERO; or if the thread is interrupted.

Here we have a total of 3 threads, each one doing certain things.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class App{
 public static void main(String[] args) {
  CountDownLatch latch = new CountDownLatch(3);//<--takes 3 because 3 threads
  ExecutorService executorService = Executors.newFixedThreadPool(3);
 
  for(int i=0; i<3; i++){
   executorService.submit(new Processor(latch));// <-- passing latch by alias.
  }
  
  System.out.println("All the threads submitted! Running 3 threads at a time!");
  
  //Causes the current thread to wait until 
  //the latch has counted down to zero, unless 
  //the thread is interrupted. 
  try {
   latch.await();
  } catch (InterruptedException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
  
  System.out.println("Completed!");
 }
}

class Processor implements Runnable{
 //Alias to hold latch that shall be passed through constructor
 private CountDownLatch latch;
 
 public Processor(CountDownLatch latch) {
  // TODO Auto-generated constructor stub
  this.latch = latch;
 }
 @Override
 public void run() {
  // TODO Auto-generated method stub
  System.out.println("Started!" + latch.getCount());
  
  try {
   Thread.sleep(3000);
  } catch (InterruptedException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
  
  //This will count-down latch by 1.
  latch.countDown();// <-- Change made here will affect original latch.
 }
 
}

No comments:

Post a Comment