English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Guava는 Java 병행 프로그래밍에서 Future에 대한 많은 유용한 확장을 제공하며, 주요 인터페이스는 ListenableFuture로, Futures 스태틱 확장을 통해 지원됩니다.
Future를 상속한 ListenableFuture는, 스레드 작업이 완료되거나 메서드 실행이 즉시 완료될 때 반환 값을 추가할 수 있는 기능을 제공합니다.
ListenableFuture에 콜백 함수 추가:
Futures.addCallback(ListenableFuture<V>, FutureCallback<V>, Executor)
FutureCallback은 onSuccess(V), onFailure(Throwable)를 포함한 인터페이스입니다.
사용 예:
Futures.addCallback(ListenableFuture, new FutureCallback<Object>() { public void onSuccess(Object result) { System.out.printf("onSuccess with: %s%n", result); } public void onFailure(Throwable thrown) { System.out.printf("onFailure %s%n", thrown.getMessage()); } });
Guava의 Futures는 Future 확장에 대해 다음과 같습니다:
아래는 Future에 대한 테스트 데모입니다:
@Test public void should_test_furture() throws Exception { ListeningExecutorService service = MoreExecutors.listeningDecorator(Executors.newFixedThreadPool(10)); ListenableFuture future1 = service.submit(new Callable<Integer>() { public Integer call() throws InterruptedException { Thread.sleep(1000); System.out.println("call future 1."); return 1; } }); ListenableFuture future2 = service.submit(new Callable<Integer>() { public Integer call() throws InterruptedException { Thread.sleep(1000); System.out.println("call future 2."); // throw new RuntimeException("----call future 2."); return 2; } }); final ListenableFuture allFutures = Futures.allAsList(future1, future2); final ListenableFuture transform = Futures.transform(allFutures, new AsyncFunction<List<Integer>, Boolean>() { @Override public ListenableFuture apply(List<Integer> results) throws Exception { return Futures.immediateFuture(String.format("성공 future:%d", results.size())); } }); Futures.addCallback(transform, new FutureCallback<Object>() { public void onSuccess(Object result) { System.out.println(result.getClass()); System.out.printf("success with: %s%n", result); } public void onFailure(Throwable thrown) { System.out.printf("onFailure%s%n", thrown.getMessage()); } }); System.out.println(transform.get()); }
공식 자료 메인 페이지:https://awk.so/@code.google.com!/p/guava-라이브러리/위키/ListenableFutureExplained
Guava에 대한 설명은 이렇습니다. - 병행 프로그래밍 Futures 자료 정리, 이어서 관련 자료를 추가할 예정입니다. 감사합니다.
성명: 본 내용은 인터넷에서 수집되었으며, 저작권자는 모두 소유합니다. 내용은 인터넷 사용자가 자발적으로 기여하고 업로드한 것이며, 이 사이트는 소유권을 가지지 않으며, 인공 편집 처리를 하지 않았으며, 관련 법적 책임도 부담하지 않습니다. 저작권 침해가 의심되는 내용이 있으시면, notice#w로 이메일을 보내 주시기 바랍니다.3codebox.com(이메일을 보내는 경우, #을 @으로 변경하십시오. 신고하시고 관련 증거를 제공하시면, 해당 내용이 실제로 침해된 것으로 확인되면, 이 사이트는 즉시 해당 내용을 삭제합니다.)