I would like to achieve the following behaviour using ExecutorService from Java. I have a large number of tasks to complete which can all be done in parallel. I would like to schedule from my main thread only N tasks at the time in the following manner:
- if the number of active tasks is < N => schedule new task (executor service does that already)
- else, block on the main thread until one of the tasks is done => pretty much the same as storing N first tasks in the queue and then dequeing the first and calling get() on it)
Is there a way to tweak the ExecutorService to do as stated above?
Use a ThreadPoolExecutor of N threads, constructed with a SynchronousQueue. Each time you’ll submit a task to the thread pool, the main thread will be blocked by the synchronous queue until a thread from the pool takes the task from the queue.