Java execute multiple Threads and wait for completion

Viewed 216

I'm writing a small program which is supposed to update Firmware on Servers. The way I currently do this is by issuing a command via the ProcessBuilder, executing it and using exitCode = process.waitFor(); to wait until the command is finished.

Some of these Firmware updates can take a few minutes, so when setting up multiple Systems, these Firmware updates can take hours, if done separately.

I have tried creating Threads, while using CyclicBarrier, to ensure that all Firmware Updates are started at the same time. (See: Stackoverflow-Question: How to start two threads at “exactly” the same time

The problem I have spotted with this however, that my program will continue as usual after starting all the threads - which in this case would be to reboot all the systems, which might break them if they are still in the process of updating Firmware.

How could I ensure that all Firmware Updates are done before continuing? I have thought about letting the program sleep for 10-15 minutes, but would like a more reliable approach.

2 Answers

You may use a CountDownLatch in addition to the barrier. Pass the CountDownLatch to each of the thread, once the firmware update is completed, just call the count-down on the latch. In your main thread, after starting all the threads, you may wait by calling latch.await and it will wail till all the other threads finish. You may find a sample here.

You can even use a CountDownLatch with 1 as the count for the starting gun in your case, which precludes the use of the CyclicBarrier.

You need Thread.join() method. Take a look at the example:

public static void main(String[] args) throws InterruptedException {
        Runnable sleepTwoSeconds = () -> {
            try {
                Thread.sleep(2000);
                System.out.println("Sleeping finished");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        };
        Thread t1 = new Thread(sleepTwoSeconds);
        t1.start();
        Thread t2 = new Thread(sleepTwoSeconds);
        t2.start();
        t1.join();
        t2.join();
        System.out.println("Main thread continue.");

    }

"How could I ensure that all Firmware Updates are done before continuing?" Main thread will not continue until t1 and t2 are done.

Related