Defining Asynchronous Tasks Inline using Lambdas
suggest changeWhile 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:
- A lambda can use variables and methods from the enclosing scope. Local variables must be final or effectively final.
indexis copied into a final local becauseichanges. - The lambda is a
Runnableor aCallable<Integer>because of the target method:executetakes aRunnable, and thissubmittakes aCallable. The loop polls until every future is done and does not sleep between polls.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents