Search code examples
javamultithreadingconcurrencyjava-threads

Java execute multiple Threads and wait for completion


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.


Solution

  • 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.