Skip to content

Instantly share code, notes, and snippets.

@yanhsiah
Last active April 27, 2019 07:05
Show Gist options
  • Save yanhsiah/5a89ac8f8c2703780559c7b43cafba07 to your computer and use it in GitHub Desktop.
Save yanhsiah/5a89ac8f8c2703780559c7b43cafba07 to your computer and use it in GitHub Desktop.
Use Vert.x worker threads to run a for-loop.
import io.vertx.core.*;
public class ConcurrentLoop {
private static String runTask(int idx) {
System.out.println("run task " + idx + " on " + Thread.currentThread().getName());
long sum = 0;
for (long j = 0; j < Long.MAX_VALUE / 1000000000; j++) {
sum += 1;
}
System.out.println("finish task " + idx);
return String.valueOf(sum);
}
public static void main(String[] args) {
long start1 = System.nanoTime();
runTask(0);
long end1 = System.nanoTime();
System.out.println("all done, time " + (end1 - start1) / 1000000 + " ms");
long start2 = System.nanoTime();
Vertx vertx = Vertx.vertx();
List futureList = new ArrayList();
for (int i = 0; i < 5; i++) {
Future taskFuture = Future.future();
futureList.add(taskFuture);
final int idx = i;
vertx.<String>executeBlocking(fut -> {
runTask(idx);
fut.complete();
}, false, res -> {
taskFuture.complete("result " + idx + " = " + res.result());
});
}
CompositeFuture.join(futureList).setHandler(res -> {
long end2 = System.nanoTime();
System.out.println("all done, time " + (end2 - start2) / 1000000 + " ms");
List<String> lst = res.result().list();
for (String s : lst) {
System.out.println(s);
}
});
}
}
/**
run task 0 on main
finish task 0
all done, time 5310 ms
run task 0 on vert.x-worker-thread-0
run task 1 on vert.x-worker-thread-1
run task 2 on vert.x-worker-thread-2
run task 3 on vert.x-worker-thread-3
run task 4 on vert.x-worker-thread-4
finish task 1
finish task 0
finish task 3
finish task 2
finish task 4
all done, time 13730 ms
result 0 = null
result 1 = null
result 2 = null
result 3 = null
result 4 = null
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment