fork(15) download
  1. /* package whatever; // don't place package name! */
  2.  
  3. import java.util.*;
  4. import java.util.concurrent.*;
  5. import java.util.concurrent.locks.LockSupport;
  6. import java.util.function.*;
  7.  
  8. /* Name of the class has to be "Main" only if the class is public. */
  9. class Ideone
  10. {
  11. public static void main (String[] args) throws java.lang.Exception
  12. {
  13. String s=anyOf(Arrays.asList(
  14. CompletableFuture.supplyAsync(()->{throw new RuntimeException();}),
  15. CompletableFuture.supplyAsync(()->{ LockSupport.parkNanos(10_000_000_000L); return "hello"; })))
  16. .join();
  17. System.out.println(s);
  18. }
  19. public static <T>
  20. CompletableFuture<T> anyOf(List<? extends CompletionStage<? extends T>> l) {
  21.  
  22. CompletableFuture<T> f=new CompletableFuture<>();
  23. Consumer<T> complete=f::complete;
  24. CompletableFuture.allOf(
  25. l.stream().map(s -> s.thenAccept(complete)).toArray(CompletableFuture<?>[]::new)
  26. ).exceptionally(ex -> { f.completeExceptionally(ex); return null; });
  27. return f;
  28. }
  29. }
Success #stdin #stdout 0.21s 321792KB
stdin
Standard input is empty
stdout
hello