Skip to content

Instantly share code, notes, and snippets.

@noahlz
Created June 15, 2012 14:59
Show Gist options
  • Save noahlz/2936872 to your computer and use it in GitHub Desktop.
Save noahlz/2936872 to your computer and use it in GitHub Desktop.
Toy application that demonstrates the java.util.concurrent.ExecutorCompletionService
import java.util.Random;
import java.util.concurrent.*;
/**
* App that tests completion service.
*/
public class CompletionServiceExample {
private static final int COUNT = 25;
public static void main(String[] args) {
ExecutorService executor = Executors.newFixedThreadPool(3);
CompletionService<String> cs = new ExecutorCompletionService<String>(executor);
for(int i = 0; i < COUNT; i++) {
final int taskno = i + 1;
cs.submit(new Callable<String>() {
@Override
public String call() throws Exception {
long secondsToSleep = 1000 * (new Random().nextInt(4) + 1);
Thread.sleep(secondsToSleep);
return "Task #" + taskno + " slept " +
TimeUnit.SECONDS.convert(secondsToSleep, TimeUnit.MILLISECONDS) + " seconds.";
}
});
}
executor.shutdown();
int remaining = COUNT;
while(remaining > 0) {
String result;
try {
result = cs.take().get();
System.out.println("*** " + result);
} catch (InterruptedException e) {
System.err.println("Interrupted when " + remaining + " task(s) were left: " + e.getMessage());
System.err.println("Aborting...");
break;
} catch (ExecutionException e) {
// Remember that ExecutionException wraps the root cause.
System.err.println("Could not get result: " + e.getCause().getMessage());
}
remaining--;
}
System.out.println("*** DONE ***");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment