Skip to content

Instantly share code, notes, and snippets.

@nkcoder
Created December 21, 2016 14:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nkcoder/7679cd897a3374c030c1027905704a70 to your computer and use it in GitHub Desktop.
Save nkcoder/7679cd897a3374c030c1027905704a70 to your computer and use it in GitHub Desktop.
CompletionService Test
package org.nkcoder.module.javatest.concurrent;
import java.util.concurrent.*;
/**
* Created by nkcoder on 12/21/16.
*/
public class CompletionServiceTest {
public static void main(String[] args) {
Executor executor = Executors.newFixedThreadPool(3);
CompletionService completionService = new ExecutorCompletionService(executor);
int size = 10;
for (int i = 0; i < size; i++) {
final int raw = i;
final int multiple = Math.multiplyExact(raw, raw);
completionService.submit(() -> {
System.out.println("raw = " + raw);
try {
TimeUnit.MILLISECONDS.sleep(multiple);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
return multiple;
});
}
for (int i = 0; i < size; i++) {
try {
Future future = completionService.take();
System.out.println("multiple: " + future.get());
} catch (InterruptedException | ExecutionException e) {
Thread.currentThread().interrupt();
}
}
System.out.println("done.");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment