Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to execute a piece of code only after all threads in the threads pool are done?

I want to ensure that all threads created in part1 are executed before executing the code of Part 2.

    @Override
    List<Future<ReconcileResult>> parseAndExecute(ReconcileContext context, File businessReconFile, File bcReconFile) throws Exception {

        List<Future<ReconcileResult>> reconcileResults;
        redisUtil.flushdb();
//PART1
        fileParser.parseAndTransfer(businessReconFile, bcReconFile, executeData -> {
            ThreadUtils.executor.submit(
                    () -> reconcileExecutor.execute_c(context, executeData)
            );
        });
//PART1
//PART2
        reconcileResults = reconcileExecutor.getReconcileResult(context);
//PART2
        return reconcileResults;
    }

One way I came up with is to add "Thread.sleep" between Part1 and part2, But it has great limitations.
Are there any more flexible methods?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

I think this thread is helpful:
How to wait for all threads to finish, using ExecutorService?

Based on the above link, there are plenty of ways you can use it. For example, you can call:

List<Future<?>> futures = ThreadUtils.executor.invokeAll(tasks);

or Use cantdownLatch

or call .get() on list of futures (results of your submissions to your executor):

for(Future f: this.futures) { f.get(); }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading