I'm testing Completable Future. As described here I thought thread would be reused from common pool but this snippet shows strange behaviour
for (int i = 0; i < 10000; i++) {
final int counter = i;
CompletableFuture.supplyAsync(() -> {
System.out.println("Looking up " + counter + " on thread " + Thread.currentThread().getName());
return null;
});
}
I have that kind of output:
Looking up 0 on thread Thread-2
Looking up 1 on thread Thread-3
Looking up 2 on thread Thread-4
...
Looking up 10000 on thread Thread-10002
it looks like a new thread is created for each task. Why all of my completableFuture do not reuse thread from common pool?
MoreOver I've tested with RxJava and it works as excpected with this code:
for (int i = 0; i < 10000; i++) {
rxJobExecute(i).subscribeOn(Schedulers.io()).subscribe();
}
private Observable<String> rxJobExecute(int i) {
return Observable.fromCallable(() -> {
System.out.println("emission " + i + " on thread " + Thread.currentThread().getName());
return "tata";
});
}
output
emission 8212 on thread RxIoScheduler-120
emission 8214 on thread RxIoScheduler-120
emission 8216 on thread RxIoScheduler-120
emission 8218 on thread RxIoScheduler-120
emission 8220 on thread RxIoScheduler-120
emission 7983 on thread RxIoScheduler-275
emission 1954 on thread RxIoScheduler-261
emission 1833 on thread RxIoScheduler-449
emission 1890 on thread RxIoScheduler-227