Created
June 15, 2012 14:59
-
-
Save noahlz/2936872 to your computer and use it in GitHub Desktop.
Toy application that demonstrates the java.util.concurrent.ExecutorCompletionService
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
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