Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.ArrayList;
- import java.util.List;
- import java.util.concurrent.*;
- import java.util.stream.Collectors;
- public class FutureTest {
- private static CompletableFuture<List<String>> getCompletableFutureResult() {
- return CompletableFuture.supplyAsync(() -> {
- try {
- TimeUnit.MILLISECONDS.sleep(2500);
- System.out.println("It async task that wait 2500 ms");
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- return getResult();
- });
- }
- private static ArrayList<String> getResult() {
- ArrayList<String> list = new ArrayList<>();
- list.add("one");
- list.add("two");
- return list;
- }
- private static CompletableFuture<List<List<String>>> testFutures() {
- int x = 3;
- List<CompletableFuture<List<String>>> futureList = new ArrayList<>();
- for (int i = 0; i < x; i++) {
- futureList.add(getCompletableFutureResult());
- }
- CompletableFuture[] futureArray = futureList.toArray(new CompletableFuture[0]);
- CompletableFuture<Void> combinedFuture = CompletableFuture.allOf(futureArray);
- return combinedFuture.thenApply(it ->
- futureList.stream().map(CompletableFuture::join).collect(Collectors.toList())
- );
- }
- public static void main(String[] args) {
- long startTime = System.currentTimeMillis();
- System.out.println("Main: " + Thread.currentThread().getName());
- int requestCount = 10;
- CountDownLatch countDownLatch = new CountDownLatch(requestCount);
- ExecutorService executorService = Executors.newFixedThreadPool(1);
- ForkJoinPool forkJoinPool = new ForkJoinPool(8);
- for (int i = 0; i < requestCount; i++) {
- executorService.execute(() -> {
- CompletableFuture.runAsync(() -> {
- System.out.println("AsyncThreadStart: " + Thread.currentThread().getName());
- testFutures().thenAccept(System.out::println).join();
- }, forkJoinPool).whenComplete((task, ex) -> {
- if (ex != null) System.out.println(ex.getMessage());
- countDownLatch.countDown();
- if (countDownLatch.getCount() == 0) {
- long endTime = System.currentTimeMillis();
- System.out.println(endTime - startTime);
- executorService.shutdown();
- }
- });
- });
- }
- System.out.println("Execution not locking");
- }
- }
Add Comment
Please, Sign In to add comment