Ashish
Ashish

Reputation: 14707

Why my threads are not completing

I am trying to understand countDownLatch and I have this program but I do not know why my program is not returning and not finishing.

package countDownLatches;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

class Processor implements Runnable {

    CountDownLatch latch;

    public Processor(CountDownLatch latch) {
        this.latch = latch;
    }

    public void run() {
        System.out.println("thread started: ");
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        latch.countDown();
    }

}

public class App {
    public static void main(String args[]) {
        CountDownLatch latch = new CountDownLatch(3);
        ExecutorService executorService = Executors.newFixedThreadPool(3);
        for (int i = 0; i < 3; i++) {
            executorService.submit(new Processor(latch));
        }
        try {
            latch.await();
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        System.out.println("task completed");
    }
}

Upvotes: 1

Views: 93

Answers (2)

Oroboros102
Oroboros102

Reputation: 2254

You need to shutdown your executor service properly. Or it will wait for new tasks indefinitely.

Add:

executorService.shutdown();

Before:

System.out.println("task completed");

I think, that the main reason, why it was done like that in java api, is that executorService may receive tasks from multiple threads (other than main), so - why should it stop, when there is no more actions in the main thread? Yes, I believe, it should not.

Upvotes: 1

Keppil
Keppil

Reputation: 46219

You need to shut down the executor service. Add this line after the for loop:

executorService.shutdown();

An alternative method that waits for all actively executing tasks to terminate is

executorService.awaitTermination();

You can read more in the ExecutorService Javadoc.

Upvotes: 3

Related Questions