Skip to content

Instantly share code, notes, and snippets.

@EdgeCaseBerg
Created February 6, 2015 19:01
Embed
What would you like to do?
ConcurrencyTest for timing out and putting a limit on tasks.
import java.util.List;
import java.util.Collection;
import java.util.ArrayList;
import java.util.concurrent.*;
import java.lang.InterruptedException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.CancellationException;
import java.util.Random;
public class ConcurrentTest {
private final ExecutorService pool = Executors.newFixedThreadPool(50);
private long getThingThatTakesAWhile(long milliSecs) throws InterruptedException{
System.out.println("Starting task that will take " + milliSecs + " milliSecs!");
Thread.sleep(milliSecs);
System.out.println("Done task that took " + milliSecs + " milliSecs!");
return milliSecs;
}
public void doStuff() {
int sizeOfList = 10;
Collection<Callable<Long>> tasks = new ArrayList<Callable<Long>>(sizeOfList);
Random rand = new Random();
for (int i =0; i < sizeOfList ; i++) {
final int j = i;
final int randomNum = rand.nextInt((4000 - 0) + 1) + 0;
tasks.add(new Callable<Long>() {
@Override
public Long call() throws InterruptedException{
return getThingThatTakesAWhile(randomNum);
}
});
}
List<Long> valuesReturned = new ArrayList<Long>(sizeOfList);
try {
List<Future<Long>> returnedResults = pool.invokeAll(tasks, 2L, TimeUnit.SECONDS);
pool.shutdown(); // do this here otherwise you will block and wait for others
for (final Future res : returnedResults) {
if (!res.isCancelled()) {
final Long cal = (Long)res.get(0,TimeUnit.SECONDS);
valuesReturned.add(cal);
}
}
/* The next three exceptions won't happen in our example ... */
} catch (InterruptedException ie) {
System.out.println("InterruptedException!");
} catch (ExecutionException ee) {
System.out.println("ExecutionException!");
} catch (TimeoutException te) {
System.out.println("TimeoutException!");
/* But this one will because we did cancel some callable's */
} catch (CancellationException ce) {
System.out.println("CancellationException!");
}
/* Will print out the first 7 since they were within the time limit */
int got = 0;
for (final long res : valuesReturned) {
System.out.println(res);
got++;
}
System.out.println("Retrieved [" + valuesReturned.size() + "/" + sizeOfList + "]");
}
public static void main(String[] args) {
ConcurrentTest ct = new ConcurrentTest();
ct.doStuff();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment