Search⌘ K
AI Features

Solution: Background Email Sender

Explore how to implement a background email sender using Java's ExecutorService with a fixed thread pool. Understand managing concurrent tasks to prevent system overload, submitting Runnable tasks with lambda expressions, and graceful shutdown of thread pools. This lesson helps you handle asynchronous operations efficiently in Java concurrency.

We'll cover the following...
Java 25
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class EmailSender {
public static void main(String[] args) {
String[] emails = {
"alice@example.com", "bob@example.com", "charlie@example.com",
"dave@example.com", "eve@example.com", "frank@example.com",
"grace@example.com", "heidi@example.com", "ivan@example.com",
"judy@example.com"
};
System.out.println("System started...");
// 1. Create a fixed thread pool with 3 threads
ExecutorService executor = Executors.newFixedThreadPool(3);
for (String email : emails) {
// 2. Submit the task using a lambda expression
executor.submit(() -> {
System.out.println("Sending email to " + email + "...");
try {
// Simulate network delay
Thread.sleep(1000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
System.out.println("Email sent to " + email + "!");
});
}
// 3. Shut down the executor to reclaim resources
executor.shutdown();
System.out.println("All tasks submitted. Main thread continues...");
}
}
...