Dylan
Dylan

Reputation: 2219

Spring - How do I run a series of threads and wait for them to finish before finishing?

Currently I have this code, I would like to use built in Spring functionality. I am using @Async for a method I do not care about when it finishes. Is there a way to use that but wait until those threads in the pool finish?

   Runnable thread = () -> {
                for (String date : dates) {

                    Path dir = Paths.get(primaryDisk, partition, folder, date);
                            File tmp = dir.toFile();
                            deleteDir(tmp);



                }
            };

            executor.submit(thread);

and later in the function I use the following code to wait for them to finish.

 executor.shutdown();

            try {
                executor.awaitTermination(5, TimeUnit.MINUTES);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

Upvotes: 3

Views: 6865

Answers (1)

JaneXQ
JaneXQ

Reputation: 420

If you use spring you can use something like this

public void doSomething(Set<String> emails){
        CompletableFuture.allOf(emails.stream()
                .map(email -> yourService.doAsync(email)
                        .exceptionally(e -> {
                            LOG.error(e.getMessage(), e);
                            return null;
                        })
                        .thenAccept(longResult -> /*do something with result if needed */))
                .toArray(CompletableFuture<?>[]::new))
            .join();
    }

This code will start every doAsync method call in other thread and will wait for all this tasks to finish.

Your doAsync method

@Async
public CompletableFuture<Long> doAsync(String email){
    //do something
    Long result = ...
    return CompletableFuture.completedFuture(result);
}

If your doSomething method and doAsync method are in same service class you should selfinject your service

@Autowired
@Lazy
private YourService yourService

and call your @Async method through this selfinjected reference(spring proxy)

yourService.doAsync(email)

to run it realy asynchronously.

Upvotes: 5

Related Questions