Mono/Flux published on ExecutorService does not terminate as expected

血红的双手。 提交于 2019-12-11 14:07:24

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!