What is the recommended way to wait for the completion of future threads to end

I am using CompletableFuture as shown below in the code. but as to how I should wait until all runnables are finished, I found two ways, and I donโ€™t know the difference between them, and which one is the best practice? they are as follows:

the code

this.growSeedFutureList = CompletableFuture.runAsync(new GrowSeedSERun(this.saliencyMat, this.seedXY, this.seedVal), this.growSeedExecutor); this.growSeedFutureList = CompletableFuture.runAsync(new GrowSeedNWRun(this.saliencyMat, this.seedXY, this.seedVal), this.growSeedExecutor); this.growSeedFutureList = CompletableFuture.runAsync(new GrowSeedNERun(this.saliencyMat, this.seedXY, this.seedVal), this.growSeedExecutor); this.growSeedFutureList = CompletableFuture.runAsync(new GrowSeedSWRun(this.saliencyMat, this.seedXY, this.seedVal), this.growSeedExecutor); 

first approach to wait for all runnables to complete

 this.growSeedExecutor.shutdown(); this.growSeedExecutor.awaitTermination(1, TimeUnit.DAYS); 

second approach to wait for all runnables to complete

 CompletableFuture.allOf(this.growSeedFutureList).join(); 

please let me know which one is recommended

+7
java multithreading concurrency completable-future
source share
1 answer

Both methods are equivalent only when the executor (growSeedExecutor) is used exclusively for this task. The first method can lead to the following: other tasks require parallelization, and a new executor is created for each task. Some developers see too many created artists and decide to use one common artist, but could not delete all the shutdown artists ...

So, the second way (join ()) is more reliable, since it is less complicated. But each new future must be added to the growSeedFutureList file, which is not assigned.

+4
source share

All Articles