Defining Asynchronous Tasks Inline using Lambdas

suggest change

While good software design often maximizes code reusability, sometimes it can be useful to define asynchronous tasks inline in your code via Lambda expressions to maximize code readability.

This class uses lambdas as a Runnable and as a Callable<Integer>. Runnable is not generic. @Log and the log field come from Lombok.

import lombok.extern.java.Log;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.*;

@Log
public class AsyncExample3 {
    public static void main(String[] args) {
        ExecutorService executorService = Executors.newCachedThreadPool();
        List<Future<Integer>> futures = new ArrayList<>();
        for(int i = 0; i < 5; i++){
            final int index = i;
            executorService.execute(() -> {
                int timeout = getTimeout();
                log.info(String.format("Runnable %d has been submitted and will sleep for %d seconds", index, timeout));
                try {
                    TimeUnit.SECONDS.sleep(timeout);
                } catch (InterruptedException e) {
                    log.warning(e.getMessage());
                }
                log.info(String.format("Runnable %d has finished sleeping", index));
            });
            Future<Integer> submittedFuture = executorService.submit(() -> {
                int timeout = getTimeout();
                log.info(String.format("Callable %d will begin sleeping", index));
                try {
                    TimeUnit.SECONDS.sleep(timeout);
                } catch (InterruptedException e) {
                    log.warning(e.getMessage());
                }
                log.info(String.format("Callable %d is done sleeping", index));
                return timeout;
            });
            futures.add(submittedFuture);
        }
        executorService.shutdown();
        while (!futures.isEmpty()) {
            Iterator<Future<Integer>> pending = futures.iterator();
            while (pending.hasNext()) {
                Future<Integer> f = pending.next();
                if (f.isDone()) {
                    try {
                        int timeout = f.get();
                        log.info(String.format("A task just completed after sleeping for %d seconds", timeout));
                        pending.remove();
                    } catch (InterruptedException | ExecutionException e) {
                        log.warning(e.getMessage());
                        pending.remove();
                    }
                }
            }
        }
    }

    public static int getTimeout(){
        return ThreadLocalRandom.current().nextInt(1, 20);
    }
}

Observations of Note:

  1. A lambda can use variables and methods from the enclosing scope. Local variables must be final or effectively final. index is copied into a final local because i changes.
  2. The lambda is a Runnable or a Callable<Integer> because of the target method: execute takes a Runnable, and this submit takes a Callable. The loop polls until every future is done and does not sleep between polls.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents