Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
//License from project: Apache License 

import java.util.ArrayList;
import java.util.List;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;

import static java.util.concurrent.Executors.newFixedThreadPool;

public class Main {
    public static <T> List<T> executeParallel(final List<Callable<T>> callables, final int maxThreadCount)
            throws InterruptedException, ExecutionException {
        final int threadCount = callables.size() > 0 && callables.size() < maxThreadCount ? callables.size()
                : maxThreadCount;
        ExecutorService executor = newFixedThreadPool(threadCount);
        List<T> results = new ArrayList<>();
        try {
            for (Future<T> future : executor.invokeAll(callables)) {
                results.add(future.get());
            }
        } finally {
            executor.shutdown();
        }
        return results;
    }
}