Last active
March 27, 2018 15:35
-
-
Save mping/8ece6ce48a7d403b81ad4e19b350abad to your computer and use it in GitHub Desktop.
CompletableFuture gotcha
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.concurrent.CompletableFuture; | |
import java.util.concurrent.ExecutionException; | |
import java.util.concurrent.TimeUnit; | |
import java.util.concurrent.TimeoutException; | |
public class FutureWUT { | |
static void sleep(long millis) { | |
try { | |
Thread.sleep(millis); | |
} catch (InterruptedException e) { | |
e.printStackTrace(); | |
} | |
} | |
public static void main(String[] args) throws InterruptedException { | |
CompletableFuture<Object> firstProcess = CompletableFuture.supplyAsync(() -> { | |
sleep(2000L); | |
System.out.println("first process"); | |
return "1"; | |
}); | |
CompletableFuture<Object> secondProcess = firstProcess.thenApplyAsync(v -> { | |
sleep(3000); | |
System.out.println("second process"); | |
return "2"; | |
}); | |
CompletableFuture<Void> completableFuture = CompletableFuture.allOf(firstProcess, secondProcess); | |
completableFuture.thenApplyAsync(v -> { | |
System.out.println("allOf completed"); | |
return "3"; | |
}); | |
try { | |
completableFuture.get(100, TimeUnit.MILLISECONDS); | |
} catch (Exception e) { | |
System.out.println("Timeout!"); | |
} | |
Thread.sleep(10000); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment