Skip to content

Instantly share code, notes, and snippets.

@sshark
Created December 17, 2020 16:13
Show Gist options
  • Select an option

  • Save sshark/36526983d243c4ab475e144aa578ccaa to your computer and use it in GitHub Desktop.

Select an option

Save sshark/36526983d243c4ab475e144aa578ccaa to your computer and use it in GitHub Desktop.
Writing a functioning CompletableFuture
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;
}
}
@sshark

sshark commented Dec 17, 2020

Copy link
Copy Markdown
Author

The first test takes about 6s to complete while the second test takes about 2s to complete

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment