Site Search:

CheckForMail.java

Back>

CheckForMail checks for mail in parallel on a set of hosts. The main thread created a new instance of CheckForMail, then sends a set of hosts to public boolean checkMail(Set<String> hosts, long timeout, TimeUnit unit) method. CheckMail method created a local ExcecutorService and submit a new runnable for each host to the ExecutorService. After finish submitting loop, the ExecutorService is shut down in finally block. When the ExecutorService is shut down, all the submitted tasks exec.execute(() -> ...); have completed.

CHAP7>cat CheckForMail.java 
import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.*;
import java.util.stream.Stream;

/**
 * CheckForMail
 * <p/>
 * Using a private \Executor whose lifetime is bounded by a method call
 */
public class CheckForMail {
    public static void main(String... args) {
        Set<String> hosts = new HashSet<>();
        Stream.iterate(0, i -> i + 1).limit(5)
                .forEach(i -> hosts.add("1.1.1." + i));
        CheckForMail cfm = new CheckForMail();
        try {
            System.out.println(cfm.checkMail(hosts, 10, TimeUnit.SECONDS));
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public boolean checkMail(Set<String> hosts, long timeout, TimeUnit unit)
            throws InterruptedException {
        ExecutorService exec = Executors.newCachedThreadPool();
        final AtomicBoolean hasNewMail = new AtomicBoolean(false);
        try {
            for (final String host : hosts)
                exec.execute(() -> {
                    if (checkMail(host))
                        hasNewMail.set(true);
                });
        } finally {
            exec.shutdown();
            exec.awaitTermination(timeout, unit);
        }
        return hasNewMail.get();
    }

    private boolean checkMail(String host) {
        // Check for mail
        System.out.println(Thread.currentThread() + " checking host " + host);
        return false;
    }
}
CHAP7>javac CheckForMail.java 
CHAP7>java CheckForMail
Thread[pool-1-thread-2,5,main] checking host 1.1.1.1
Thread[pool-1-thread-5,5,main] checking host 1.1.1.4
Thread[pool-1-thread-4,5,main] checking host 1.1.1.3
Thread[pool-1-thread-3,5,main] checking host 1.1.1.2
Thread[pool-1-thread-1,5,main] checking host 1.1.1.0
false
CHAP7>