2014-03-11 01:06:37 +00:00
|
|
|
import java.util.concurrent.Callable;
|
|
|
|
import java.util.concurrent.ExecutionException;
|
|
|
|
import java.util.concurrent.Executor;
|
|
|
|
import java.util.concurrent.ExecutorCompletionService;
|
|
|
|
import java.util.concurrent.TimeUnit;
|
|
|
|
|
2014-03-12 16:35:44 +00:00
|
|
|
public class CompletionServiceTest {
|
2014-03-11 01:06:37 +00:00
|
|
|
public static void main(String args[]) throws InterruptedException, ExecutionException {
|
|
|
|
Executor dumbExecutor = new Executor() {
|
|
|
|
@Override
|
|
|
|
public void execute(Runnable task) {
|
|
|
|
new Thread(task).start();
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
|
|
|
pollNoResultTest(dumbExecutor);
|
|
|
|
pollTimeoutNoResultTest(dumbExecutor);
|
|
|
|
takeTest(dumbExecutor);
|
|
|
|
}
|
|
|
|
|
2014-03-11 15:20:34 +00:00
|
|
|
private static void verify(boolean val) {
|
|
|
|
if (! val) {
|
|
|
|
throw new RuntimeException();
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2014-03-11 01:06:37 +00:00
|
|
|
private static void pollNoResultTest(Executor executor) {
|
|
|
|
ExecutorCompletionService<Object> ecs = new ExecutorCompletionService<Object>(executor);
|
|
|
|
|
2014-03-11 15:20:34 +00:00
|
|
|
verify(ecs.poll() == null);
|
2014-03-11 01:06:37 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
private static void pollTimeoutNoResultTest(Executor executor) throws InterruptedException {
|
|
|
|
long delayTime = 0;
|
|
|
|
ExecutorCompletionService<Object> ecs = new ExecutorCompletionService<Object>(executor);
|
|
|
|
|
|
|
|
long startTime = System.currentTimeMillis();
|
2014-03-11 15:20:34 +00:00
|
|
|
verify(ecs.poll(delayTime, TimeUnit.MILLISECONDS) == null);
|
|
|
|
verify(System.currentTimeMillis() - startTime >= delayTime);
|
2014-03-11 01:06:37 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
private static void takeTest(Executor executor) throws InterruptedException, ExecutionException {
|
|
|
|
ExecutorCompletionService<Object> ecs = new ExecutorCompletionService<Object>(executor);
|
|
|
|
final Object result = new Object();
|
|
|
|
ecs.submit(new Callable<Object>() {
|
|
|
|
@Override
|
|
|
|
public Object call() throws Exception {
|
|
|
|
return result;
|
|
|
|
}
|
|
|
|
});
|
|
|
|
|
2014-03-11 15:20:34 +00:00
|
|
|
verify(ecs.take().get() == result);
|
2014-03-11 01:06:37 +00:00
|
|
|
}
|
|
|
|
}
|