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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With