Skip to content

Instantly share code, notes, and snippets.

@yohhoy
Last active August 29, 2015 14:08
Show Gist options
  • Save yohhoy/cf2ba46d9293b2539d1e to your computer and use it in GitHub Desktop.
Save yohhoy/cf2ba46d9293b2539d1e to your computer and use it in GitHub Desktop.
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;
import java.util.concurrent.CancellationException;
public class CompletableFutureExample {
private static CompletableFuture<Optional<String>> applyTaskAsync(String s) {
return CompletableFuture.completedFuture(s)
.thenApplyAsync(Main::taskA)
.thenApplyAsync(Main::taskB)
.handle((v,ex) -> Optional.ofNullable(v));
}
public static void main(String[] args) {
try {
CompletableFuture<Optional<String>> f = applyTaskAsync("xyz");
// f.cancel(true or false):
// cancel Future object returned from handle() method,
// so taskA and taskB will continue their tasks.
System.out.println(Thread.currentThread().getId()+"join");
Optional<String> result = f.join();
System.out.println(Thread.currentThread().getId()+"result=" + result.orElse("(fail)"));
} catch (CompletionException ex) {
System.out.println("catch:" + ex.getCause());
} catch (CancellationException ex) {
System.out.println("cancelled");
}
}
private static String taskA(String s) {
sleep(100);
System.out.println(Thread.currentThread().getId() + "TaskA");
if (s == null || s.isEmpty())
throw new RuntimeException("FAIL");
return "{" + s + "}";
}
private static String taskB(String s) {
sleep(100);
System.out.println(Thread.currentThread().getId() + "TaskB");
return "(" + s + ")";
}
private static void sleep(long n) {
try { Thread.sleep(n); } catch (InterruptedException ex) {}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment