Guest User

Untitled

a guest
May 23rd, 2018
67
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.58 KB | None | 0 0
  1. import java.util.ArrayList;
  2. import java.util.List;
  3. import java.util.concurrent.*;
  4. import java.util.stream.Collectors;
  5.  
  6. public class FutureTest {
  7. private static CompletableFuture<List<String>> getCompletableFutureResult() {
  8. return CompletableFuture.supplyAsync(() -> {
  9. try {
  10. TimeUnit.MILLISECONDS.sleep(2500);
  11. System.out.println("It async task that wait 2500 ms");
  12. } catch (InterruptedException e) {
  13. e.printStackTrace();
  14. }
  15. return getResult();
  16. });
  17. }
  18.  
  19. private static ArrayList<String> getResult() {
  20. ArrayList<String> list = new ArrayList<>();
  21. list.add("one");
  22. list.add("two");
  23. return list;
  24. }
  25.  
  26. private static CompletableFuture<List<List<String>>> testFutures() {
  27. int x = 3;
  28. List<CompletableFuture<List<String>>> futureList = new ArrayList<>();
  29. for (int i = 0; i < x; i++) {
  30. futureList.add(getCompletableFutureResult());
  31. }
  32.  
  33. CompletableFuture[] futureArray = futureList.toArray(new CompletableFuture[0]);
  34. CompletableFuture<Void> combinedFuture = CompletableFuture.allOf(futureArray);
  35.  
  36. return combinedFuture.thenApply(it ->
  37. futureList.stream().map(CompletableFuture::join).collect(Collectors.toList())
  38. );
  39. }
  40.  
  41. public static void main(String[] args) {
  42. long startTime = System.currentTimeMillis();
  43. System.out.println("Main: " + Thread.currentThread().getName());
  44. int requestCount = 10;
  45. CountDownLatch countDownLatch = new CountDownLatch(requestCount);
  46.  
  47. ExecutorService executorService = Executors.newFixedThreadPool(1);
  48. ForkJoinPool forkJoinPool = new ForkJoinPool(8);
  49.  
  50. for (int i = 0; i < requestCount; i++) {
  51. executorService.execute(() -> {
  52. CompletableFuture.runAsync(() -> {
  53. System.out.println("AsyncThreadStart: " + Thread.currentThread().getName());
  54. testFutures().thenAccept(System.out::println).join();
  55. }, forkJoinPool).whenComplete((task, ex) -> {
  56. if (ex != null) System.out.println(ex.getMessage());
  57. countDownLatch.countDown();
  58. if (countDownLatch.getCount() == 0) {
  59. long endTime = System.currentTimeMillis();
  60. System.out.println(endTime - startTime);
  61. executorService.shutdown();
  62. }
  63. });
  64. });
  65. }
  66.  
  67. System.out.println("Execution not locking");
  68. }
  69. }
Add Comment
Please, Sign In to add comment