Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CompletableFuture runAsync vs Executing each Runnable with an Executor

Recently I'm trying to implement an email service that sends email to each user concurrently. My current implementation current looks like this:

ExecutorService executor = Executors.newSingleThreadExecutor();
tasks.forEach(executor::execute); // Each task sends an email to an user
executorService.shutdown(); // Reclaim all the resources

After some research I've found a new way, using Java 8 CompletableFuture.runAsync(...) method. Using this approach I've did:

ExecutorService executor = Executors.newSingleThreadExecutor();
tasks.forEach(task -> CompletableFuture.runAsync(task, executor));
executor.shutdown(); // Reclaim all resources

Now I'm a little confused what is the best approach for my problem in terms of correctness, scalability and what is the most modern/current approach that solves my problem.

like image 326
Călin Calin Avatar asked Jan 01 '23 23:01

Călin Calin


1 Answers

Executor.execute will execute your task asynchronously.

CompletableFuture.runAsync(Runnable, Executor) also execute your task asynchronously, but, in additionally, return a CompletableFuture object, which you can use to chain / plug more dependent tasks.

(Ex, after send email, you want to send a notify to yourself indicate the success:

CompletableFuture.runAsync(task, executor).thenRunAsync(this::sendNotify) 

For your use case, it makes no different.

You can stick with first version of code for simplicity.

like image 138
Mạnh Quyết Nguyễn Avatar answered Jan 04 '23 13:01

Mạnh Quyết Nguyễn