Right now I have this Groovy code to run a series of tasks:
CountDownLatch latch = new CountDownLatch(tasks.size);
for( task in tasks ) {
Thread.start worker.curry(task, latch)
}
latch.await(300L, TimeUnit.SECONDS);
I’d like to limit the number of simultaneous threads to a certain number t. The way it’s written now, for n tasks, n threads get created “at once”. I thought about using multiple latches or some sort of callback, but couldn’t come up with a good solution.
The solution should start new task threads as soon as running threads drops below t, until number running reaches t or there are no un-run tasks.
You can use the Executor framework.
This will create n and only n threads on start. Then you can submit to the executor to utilize these threads.
Edit: Thanks for the comment Josh, I’ll post your solution