问题
I tested a little around with the proposal in this thread: flux within executorservice
and i have simplified the example a little to understand it easier. So, heres the example:
ExecutorService executorService = Executors.newSingleThreadExecutor();
Flux.just("1", "2", "3").subscribeOn(Schedulers.fromExecutorService(executorService)).doOnNext(System.out::println).subscribe();
try {
executorService.awaitTermination(10, TimeUnit.SECONDS);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
executorService.shutdownNow();
}
But, now if this is executed it always waits the 10 seconds before the main thread ends. What was i expecting? I expected the executor service waiting 10 seconds at max until going on and calling shutdown. Normally it should be done in a few milliseconds and returning immediately after printing 1, 2, 3. The javadoc says here:
Blocks until all tasks have completed execution after a shutdown request, or the timeout occurs, or the current thread is interrupted, whichever happens first.
I don't get it. Whats wrong here?
Another sample that runs and ends immediately(but wrong in my opinion) is this one:
ExecutorService executorService = Executors.newSingleThreadExecutor();
Flux.range(1, 1_000_000).subscribeOn(Schedulers.fromExecutorService(executorService)).doOnNext(System.out::println).subscribe();
executorService.shutdownNow();
BUT, here i would have expected that the main thread doesn't wait until completion of flux (resp. the executor service). But it does. In my understanding the two examples are behaving totally upside down according to the javadoc description. javadoc says:
This method does not wait for actively executing tasks to terminate. Use awaitTermination to do that.
Any ideas?
Regards Bernado
来源:https://stackoverflow.com/questions/58800532/mono-flux-published-on-executorservice-does-not-terminate-as-expected