English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Guava - 병렬 프로그래밍 Futures 상세 설명

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 확장에 대해 다음과 같습니다:

  1. transform: ListenableFuture의 반환 값을 변환합니다.
  2. allAsList: 여러 ListenableFuture를 병합하여, 모든 Future가 성공할 때 여러 Future 반환 값을 구성한 List 객체를 반환합니다. 주의: 하나의 Future가 실패하거나 취소되면, 실패 또는 취소로 이동합니다.
  3. successfulAsList: allAsList과 유사하지만, 실패하거나 취소된 Future 반환 값을 null로 대체합니다. 실패 또는 취소 과정에 들어가지 않습니다.
  4. immediateFuture/immediateCancelledFuture: 즉시 반환할 값을 가진 ListenableFuture를 반환합니다.
  5. makeChecked: ListenableFuture를 CheckedFuture로 변환합니다. CheckedFuture는 ListenableFuture로, 여러 버전의 get 메서드를 포함하고 있으며, 메서드 선언에서 검사된 예외를 던집니다. 이렇게 하면 실행 로직에서 예외를 던질 수 있는 Future를 생성하는 것이 더 쉬워집니다.
  6. JdkFutureAdapters.listenInPoolThread(future): guava는 JDK Future를 ListenableFuture로 변환하는 인터페이스 함수도 제공합니다。

아래는 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(이메일을 보내는 경우, #을 @으로 변경하십시오. 신고하시고 관련 증거를 제공하시면, 해당 내용이 실제로 침해된 것으로 확인되면, 이 사이트는 즉시 해당 내용을 삭제합니다.)

추천해요