Sobes.tech
Junior — Middle

How can sending emails using ExecutorService for parallel processing be implemented?

sobes.tech AI

Answer from AI

To send emails using ExecutorService, you can create a thread pool where each thread handles an email sending task. This allows parallel sending without blocking the main thread.

Example:

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class EmailSender {
    private final ExecutorService executor = Executors.newFixedThreadPool(5);

    public void sendEmail(String recipient, String subject, String body) {
        executor.submit(() -> {
            // Email sending logic (e.g., via JavaMail API)
            System.out.println("Sending email " + subject + " to " + recipient);
            // Sending code here
        });
    }

    public void shutdown() {
        executor.shutdown();
    }
}

This approach allows sending multiple emails simultaneously, improving performance during mass mailing.

How can sending emails using ExecutorService for… - sobes.tech