Skip to content

Instantly share code, notes, and snippets.

@Undersent
Created July 8, 2019 18:01
Show Gist options
  • Save Undersent/1a457c6524e98f56261e7887996f73f8 to your computer and use it in GitHub Desktop.
Save Undersent/1a457c6524e98f56261e7887996f73f8 to your computer and use it in GitHub Desktop.
import java.util.Collection;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class Main {
public static void main(String[] args) {
System.out.println("App started");
// TASKS
final Runnable runnable11 = () -> {
System.out.println("List 1, task 1");
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
};
final Runnable runnable12 = () -> System.out.println("List 1, task 2");
final Runnable runnable21 = () -> {
System.out.println("List 2, task 1");
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
throw new RuntimeException("Error");
};
final Runnable runnable22 = () -> System.out.println("List 2, task 2");
final List<CompletableFuture<Void>> completableFutures = runList(runnable11, runnable12);
final List<CompletableFuture<Void>> completableFutures1 = runList(runnable21, runnable22);
Stream.of(completableFutures, completableFutures1)
.flatMap(Collection::stream)
.forEach(CompletableFuture::join);
}
private static List<CompletableFuture<Void>> runList(Runnable... runnables) {
return Stream.of(runnables).
map(runnable -> CompletableFuture.runAsync(runnable)
.whenComplete((finished, exc) -> handleTaskResult(exc))
.exceptionally(Main::handleExceptionallyResult))
.collect(Collectors.toList());
}
private static Void handleExceptionallyResult(Throwable exc) {
System.err.println("Task endded with error " + exc.getMessage());
return null;
}
private static void handleTaskResult(Throwable exc) {
if (exc == null) {
System.out.println("Task completed");
} else {
System.err.println("ERROR in runnable " + exc.getMessage());
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment