Search code examples
javamultithreadingjava-threads

Is there a better way to use a CountUpDownLatch than Await?


I'm using a count up/down latch to keep a program limited to 6 threads, it works but what I really want is to always have 6 threads running. So that when one thread dies, another one starts up. With the implementation below, it only creates 6 new threads at a time, whenever the timeout expires.

Any suggestions on how to struct my loop to accomplish this?

int numThreads = 6;

CountUpDownLatch threadCounter = new CountUpDownLatch();

for(int t = 1; t <= numThreads; t++) {
    while(list.hasNext()) {

    new Thread(new ThreadController("processData",list.next())).start();

    threadCounter.countUp();
    }
    try {
        threadCounter.await(5, TimeUnit.MINUTES);
    } catch (InterruptedException e) { e.printStackTrace(); }
}

Solution

  • Use an executor service which contains 6 threads like so,

    ExecutorService exec = Executors.newFixedThreadPool(6);
    for (int i = 0; i < 10; i++) {
        exec.submit(() -> System.out.println("Hello"));
    }
    exec.shutdown();
    

    You can either pass a Runnable or a Callable to the submit method of the ExecutorService. Here I have passed a lambda function as a Runnable which is valid starting from Java8. In your case you may do it like so,

    exec.submit(new ThreadController("processData",list.next()));