Search code examples
javaspring-bootevent-listenercompletable-futurethreadpoolexecutor

Method called using annotation '@EventListener(ApplicationReadyEvent.class)' working as expected, but direct call falls


When the method is called by @EventListener(ApplicationReadyEvent.class), the expected behavior eventually occurs. But when a direct method call occurs, then the loop inside CompletableFuture repeats only once

    @EventListener(ApplicationReadyEvent.class)
    public void method1() {

        List<CompletableFuture<Void>> pool = new ArrayList<>();
        IntStream.range(0, configproperty.getPipelinethreads()).forEach(i -> pool.add(method2()));
        CompletableFuture.allOf(pool.toArray(CompletableFuture[]::new))
                .thenRun(() -> {
                    log.info("Delta time - " + calcDeltaTime(timeBegin));
                });
    }

    private CompletableFuture<Void> method2() {

        return CompletableFuture.runAsync(() -> {
            do {
                List<Entity> entityList = facility.fetchEntityList();

                entityList.forEach(entity -> {

                    performStore(entity);
                });
            } while (proceed.get());
        }, asyncThreadPool);//ThreadPoolTaskExecutor
    }

asyncThreadPool pool got a capacity also from configproperty.getPipelinethreads()

I have tried run it using @EventListener(ApplicationReadyEvent.class) in controller's method and it working properly, but direct call the controller make it motionless after few iterations in CompletableFuture. Where should I look to find the essence of the problem?


Solution

  • Problem was solved by deleting Completablefuture. I mistakenly believed reuse thread when asyncThreadPool complete its task. In my case I decide don't pass DB operation in another thread and make task inside main thread.