I have a program where a bunch of threads carry out some task. I want to know when all these threads are finished so that I can do some other stuff with their results. I don’t want to use things like Thread.join. What I prefer is another thread checking on all these threads and when it sees that they are finished, it carries out some special task. Any ideas about how this can be done ?
I have a program where a bunch of threads carry out some task. I
Share
Actually blocking is much easier to implement, more reliable and does not introduce any extra overhead/latency. If you don’t want to use
join(), considerCountDownLatch, which allows you to wait for a set of threads.Another, much more pleasant approach is
ExecutorServicewrapped with lightweightExecutorCompletionService.Both approaches can be used in a non-blocking fashion, e.g. only peeking rather than blocking and waiting for a result. But in order not to waste CPU cycles, have a separate background thread blocking and waiting for a result and sending some event immediately when all worker threads are done.
Alternatively let each worker thread send an event when it’s done. The object that receives these events will know the processing is done once the number of received events reaches the number of workers started. With
ListenableFuturefrom Guava you can even avoid extra watchdog thread.