1

what will be output of following java prgram - Will it always be as mentioned below or there is any corner case when it can be different -

Expected output -
task1 critical section completed
task2 critical section completed

Java program -

import java.util.concurrent.CountDownLatch;

public class CountDownLatchTest2 {

public static void main(String[] args) {

    CountDownLatch countDownLatch = new CountDownLatch(1);

    RunnableTask1 task1 = new RunnableTask1(countDownLatch);
    RunnableTask2 task2 = new RunnableTask2(countDownLatch);

    Thread t2 = new Thread(task2);
    Thread t1 = new Thread(task1);

    t1.start();
    t2.start();
}

static class RunnableTask1 implements Runnable
{
    private CountDownLatch countDownLatch;

    public RunnableTask1(CountDownLatch countDownLatch) 
    {
        this.countDownLatch = countDownLatch;
    }

    @Override
    public void run()
    {
        System.out.println("task1 critical section completed");
        countDownLatch.countDown();
    }
}

static class RunnableTask2 implements Runnable
{
    private CountDownLatch countDownLatch;

    public RunnableTask2(CountDownLatch countDownLatch) 
    {
        this.countDownLatch = countDownLatch;
    }

    @Override
    public void run()
    {
        try
        {
            countDownLatch.await();
            System.out.println("task2 critical section completed");
        }
        catch (InterruptedException e) 
        {
            System.out.println("task 2 has been interupted");
        }           
    }
}
}
YoungHobbit
  • 13,254
  • 9
  • 50
  • 73

1 Answers1

1

The output will always be the expected one.

System.out.println("task1 critical section completed"); happens before countDownLatch.countDown(); which happens before countDownLatch.await(); unblocks.

Jean Logeart
  • 52,687
  • 11
  • 83
  • 118