Java timeout multiple tasks in parallel
<p>What is the best practice approach to launch a pool of 1000's of tasks (where up to 4 should be able to execute in parallel) and automatically timeout them if they take more than 3 seconds (individually)?</p>

<p>While I found that <code>ExecutorService</code> seems to be helpful (see SSCE from another post below), I don't see how to make this work for multiple tasks running in parallel (as the <code>future.get(3, TimeUnit.SECONDS)</code> is executing on the same thread than the one launching the tasks, hence no opportunity to launch multiple tasks in parallel):</p>

<pre><code>import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class Test {
    public static void main(String[] args) throws Exception {
        ExecutorService executor = Executors.newSingleThreadExecutor();
        Future&lt;String&gt; future = executor.submit(new Task());

        try {
            System.out.println("Started..");
            System.out.println(future.get(3, TimeUnit.SECONDS));
            System.out.println("Finished!");
        } catch (TimeoutException e) {
            future.cancel(true);
            System.out.println("Terminated!");
        }

        executor.shutdownNow();
    }
}

class Task implements Callable&lt;String&gt; {
    @Override
    public String call() throws Exception {
        Thread.sleep(4000); // Just to demo a long running task of 4 seconds.
        return "Ready!";
    }
}
</code></pre>

<p>Thanks!</p>