Page tree

Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Code Block
languagejava
themeEclipse
titleAsyncResult
collapsetrue
2020-01-29 18:47:21.204  INFO 86265 --- [           main] ib.ListenableFutureTest                  : asyncRestTemplateTest
2020-01-29 18:47:21.459  INFO 86265 --- [ntLoopGroup-2-1] ib.ListenableFutureTest                  : success callback
2020-01-29 18:47:21.460  INFO 86265 --- [           main] ib.ListenableFutureTest                  : result <301,<HTML><HEAD><me...
2020-01-29 18:47:21.485  INFO 86265 --- [extShutdownHook] o.s.s.c.ThreadPoolTaskScheduler          : Shutting down ExecutorService 'taskScheduler'




2. ListenableFutureCompletableFuture

  • 1의 callback 지옥 대신, 선언형으로 callback 구현 가능. (코드 가독성이 좋아진다. )

...

Code Block
languagejava
themeRDark
titleCompletableAllof
linenumberstrue
collapsetrue


		private String print(int index) {
		try {
			Thread.sleep((5+index) * 1000L);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		String str = "Completed!!" + index;
		log.info(str);
		return str;
	}

	@Test
	public void allOfTest() throws Exception {
		log.info("allOfTest START");
		
		CompletableFuture<String> cf1 = CompletableFuture.supplyAsync(() -> print(0)); //sleep 5
		CompletableFuture<String> cf2 = CompletableFuture.supplyAsync(() -> print(1)); //sleep 6
		CompletableFuture<String> cf3 = CompletableFuture.supplyAsync(() -> print(2)); //sleep 7

		// callback 에서 머지하지 않는 경우
		CompletableFuture.allOf(cf1, cf2, cf3).thenAcceptAsync(s -> log.info("result 1: {}", s));            

		// wait until they are all done
		List<CompletableFuture<String>> completableFutures = Arrays.asList(cf1, cf2, cf3);

		CompletableFuture.allOf(completableFutures.toArray(new CompletableFuture[3]))
				.thenApplyAsync(
						result -> completableFutures.stream().map(future -> future.join()).collect(Collectors.toList()))
				.thenAcceptAsync(messages -> messages.forEach(message -> log.info("result 2: {}", message)));   //몇 초 뒤 찍힐까요?

		log.info("allOfTest END");  // 몇 초 뒤에 찍힐까요?

		Thread.sleep(11 * 1000L);
	}

...