Skip to content

Instantly share code, notes, and snippets.

@ugurcanlacin
Created January 30, 2020 14:49
Show Gist options
  • Save ugurcanlacin/67850baea1c2c3394e98f67e4a70aa36 to your computer and use it in GitHub Desktop.
Save ugurcanlacin/67850baea1c2c3394e98f67e4a70aa36 to your computer and use it in GitHub Desktop.
CompletableFuture test with time benchmark
import org.apache.commons.lang3.time.StopWatch;
import org.junit.Assert;
import org.junit.Test;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class CompatableFutureTest {
@Test
public void test() {
StopWatch watch = new StopWatch();
watch.start();
CompletableFuture<String> future1
= CompletableFuture.supplyAsync(() -> {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
return "Hello";
});
CompletableFuture<String> future2
= CompletableFuture.supplyAsync(() -> {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
return "Beautiful";
});
CompletableFuture<String> future3
= CompletableFuture.supplyAsync(() -> {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
return "World";
});
CompletableFuture<String> future4
= CompletableFuture.supplyAsync(() -> {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
return "Yay!";
});
String combined = Stream.of(future1, future2, future3, future4)
.map(CompletableFuture::join)
.collect(Collectors.joining(" "));
Assert.assertEquals("Hello Beautiful World Yay!", combined);
watch.stop();
System.out.println("Time Elapsed: " + watch.getTime());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment