Search code examples
springconcurrencyspring-integrationterminate

Spring integration concurrency - detecting completion


I have a spring integration workflow that embeds task executors in its channels so as to enable concurrent processing. I manually fire off processing via a gateway and need to block the main thread until all asynchronous processes have completed. Is there a way to accomplish this? I have tried thinking along the lines of barriers, latches, and channel interceptors, but no solution is forthcoming. Any ideas anyone?


Solution

  • To answer my own question, here's what I ended up doing:

    • Create a customized ExecutorService that knows when to shutdown - in my case this was simply when releasing the last active thread - i.e. after executing the last piece in the workflow:
    
    public class WorkflowThreadPoolExecutor extends ScheduledThreadPoolExecutor {
        public WorkflowThreadPoolExecutor(int corePoolSize) {
            super(corePoolSize);
        }
    
        @Override
        protected void afterExecute(Runnable r, Throwable t) {
            super.afterExecute(r, t);
    
            if (getActiveCount() == 1) {
                shutdown();
            }
        }
    }
    
    • Await executor termination in main thread as follws:
    
        try {
            executorService.awaitTermination(Integer.MAX_VALUE, TimeUnit.SECONDS);
        } catch (InterruptedException ex) {
            LOG.error("message=Error awaiting termination of executor", ex);
        }
    

    Hope this helps someone else facing a similar issue.