Skip to content

Instantly share code, notes, and snippets.

@schmohlio
Created August 28, 2018 14:44
Show Gist options
  • Save schmohlio/0fdda77f161851fe9c6256e840773aec to your computer and use it in GitHub Desktop.
Save schmohlio/0fdda77f161851fe9c6256e840773aec to your computer and use it in GitHub Desktop.
package latch.common.utils;
import com.google.common.collect.Lists;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
public class ThrottledTaskInvoker<T> {
private final ExecutorService executorService;
public ThrottledTaskInvoker(ExecutorService executorService) {
this.executorService = executorService;
}
public List<T> invoke(List<Callable<T>> tasks, int maxThreadsAtATime) throws ExecutionException, InterruptedException {
List<List<Callable<T>>> subTasks = Lists.partition(tasks, maxThreadsAtATime);
List<T> results = Lists.newArrayListWithExpectedSize(tasks.size());
for (List<Callable<T>> subTask : subTasks) {
invokeSubTasks(results, subTask);
}
return results;
}
private void invokeSubTasks(List<T> results, List<Callable<T>> subTasks) throws InterruptedException, ExecutionException {
List<Future<T>> futures = executorService.invokeAll(subTasks);
for (Future<T> f : futures) {
results.add(f.get());
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment