Last active
August 29, 2015 13:58
Java: FutureTask demo - ConcurrencyHelper.class
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.pelssers.futuretask; | |
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.Executors; | |
import java.util.concurrent.FutureTask; | |
public final class ConcurrencyHelper { | |
public static <T> List<T> getResults(final Iterable<Callable<T>> callables, final int numberOfThreads, | |
final int sleepInMillis) throws InterruptedException, ExecutionException { | |
final List<T> results = new ArrayList<T>(); | |
final ExecutorService executor = Executors.newFixedThreadPool(numberOfThreads); | |
final List<FutureTask<T>> tasks = mapToFutureTasks(callables); | |
for (final FutureTask<T> task : tasks) { | |
executor.execute(task); | |
} | |
boolean isFinished = isDone(tasks); | |
while (!isFinished) { | |
try { | |
Thread.sleep(sleepInMillis); | |
isFinished = isDone(tasks); | |
} catch (final InterruptedException e) { | |
} | |
} | |
for (final FutureTask<T> task : tasks) { | |
results.add(task.get()); | |
} | |
executor.shutdown(); | |
return results; | |
} | |
private static <T> List<FutureTask<T>> mapToFutureTasks(final Iterable<Callable<T>> callables) { | |
final List<FutureTask<T>> futureTasks = new ArrayList<FutureTask<T>>(); | |
for (final Callable<T> callable : callables) { | |
futureTasks.add(new FutureTask<T>(callable)); | |
} | |
return futureTasks; | |
} | |
private static <T> boolean isDone(final Iterable<FutureTask<T>> tasks) { | |
final boolean isDone = true; | |
for (final FutureTask<T> task : tasks) { | |
if (!task.isDone()) { | |
return false; | |
} | |
} | |
return isDone; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment