Created
December 17, 2020 16:13
-
-
Save sshark/36526983d243c4ab475e144aa578ccaa to your computer and use it in GitHub Desktop.
Writing a functioning CompletableFuture
This file contains hidden or 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
| package org.teckhooi; | |
| import java.util.concurrent.CompletableFuture; | |
| public class RealAsync { | |
| public static void main(String[] args) { | |
| long waitTime = 2000; | |
| System.out.println("Test 1 starts..."); | |
| long timeTaken = time(() -> { | |
| CompletableFuture[] futures = new CompletableFuture[3]; | |
| for (int i = 0; i < 3; i++) { | |
| futures[i] = CompletableFuture.completedFuture(complexProcess(waitTime)); | |
| } | |
| CompletableFuture.allOf(futures).join(); | |
| }); | |
| System.out.println("Test 1 completes."); | |
| System.out.printf("First test took %dms\n", timeTaken); | |
| System.out.println("Test 2 starts..."); | |
| timeTaken = time(() -> { | |
| CompletableFuture[] futures = new CompletableFuture[3]; | |
| for (int i = 0; i < 3; i++) { | |
| futures[i] = CompletableFuture.supplyAsync(() -> complexProcess(waitTime)); | |
| } | |
| CompletableFuture.allOf(futures).join(); | |
| }); | |
| System.out.println("Test 2 completes."); | |
| System.out.printf("Second test took %dms\n", timeTaken); | |
| } | |
| static public long complexProcess(long waitTime) { | |
| try { | |
| Thread.sleep(waitTime); | |
| } catch (InterruptedException e) { | |
| // Empty | |
| } | |
| return waitTime; | |
| } | |
| static public long time(Runnable block) { | |
| long now = System.currentTimeMillis(); | |
| block.run(); | |
| return System.currentTimeMillis() - now; | |
| } | |
| } |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The first test takes about 6s to complete while the second test takes about 2s to complete