Last active
August 29, 2015 14:08
-
-
Save yohhoy/cf2ba46d9293b2539d1e to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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