0

I am using an

ExecutorService executor = Executors.newFixedThreadPool(4);

to pass Runnable threads for multi-threaded Java and need a barrier where the program waits until all threads that have been submitted to the ThreadPool's queue so far have finished execution. Afterwards I want to continue filling the queue again. This procedure is iterated in a for-loop.

Is there an efficient method, which does not require to always shutdown the ExecutorService and instantiate a new one?

madison54
  • 743
  • 2
  • 8
  • 19
  • 2
    What is wrong with shutting down the service and creating a new one? Have you proven that it's too inefficient for your needs or are you just assuming it's a bad approach without testing it? – Duncan Jones Dec 16 '14 at 10:54
  • you can check `getActiveCount()` method on ThreadPoolExecutor. It's not available in ExecutorService. – Adi Dec 16 '14 at 10:57
  • You don't need to that, fixed thread pool ExecutorService has queue of tasks from which it uses for picking up – manzur Dec 16 '14 at 10:59
  • 1
    Why do you want that exactly? – fge Dec 16 '14 at 11:00
  • @Duncan Yes, I am assuming that shutting one down and creating a new ExecutorService is inefficient. Am I wrong? – madison54 Dec 16 '14 at 11:06
  • 2
    @madison54 I don't know, it depends on so many things. But it appears to be a simple solution and one shouldn't prematurely optimise simple solutions unless they prove to be a bottleneck. – Duncan Jones Dec 16 '14 at 11:07
  • @fge At the end of every iteration of this procedure I need to work with ALL results passed so far, so all must have finished before adding new ones in another iteration of the for-loop. – madison54 Dec 16 '14 at 11:08
  • @madison54 pls be specific: either you want to wait the queue is empty, or wait all results passed. The difference is that when the queue becomes empty, not all results passed - some are still processed by the pool's threads. – Alexei Kaigorodov Dec 16 '14 at 13:43
  • All threads should have finished execution. – madison54 Dec 19 '14 at 16:16

0 Answers0