programing tip

CompletableFuture, Future 및 RxJava의 Observable의 차이점

itbloger 2020. 5. 30. 22:19
반응형

CompletableFuture, Future 및 RxJava의 Observable의 차이점


나는 사이의 차이를 알고 싶습니다 CompletableFuture, Future그리고 Observable RxJava.

내가 아는 것은 모두 비동기이지만

Future.get() 실을 막다

CompletableFuture 콜백 메소드를 제공합니다

RxJava Observable--- CompletableFuture다른 혜택 과 유사 (확실하지 않음)

예를 들어, 클라이언트가 여러 서비스 호출을해야하고 우리가 사용할 때 Futures(Java) Future.get()가 순차적으로 실행될 경우 ... RxJava에서 어떻게 더 나은지 알고 싶습니다.

그리고 http://reactivex.io/intro.html 문서 에는

선물을 사용하여 조건부 비동기 실행 흐름을 최적으로 구성하는 것은 어렵습니다 (또는 각 요청의 대기 시간은 런타임에 따라 다르므로 불가능합니다). 물론이 작업을 수행 할 수는 있지만 빠르게 복잡해 지거나 오류가 발생하기 쉬워 지거나 Future.get ()에서 조기에 차단되므로 비동기 실행의 이점이 사라집니다.

RxJava이 문제를 어떻게 해결 하는지 알고 싶습니다 . 설명서에서 이해하기 어렵다는 것을 알았습니다.


선물

선물 은 Java 5 (2004)에 도입되었습니다. 기본적으로 아직 완료되지 않은 작업의 결과에 대한 자리 표시 자입니다. 작업이 완료되면에 Future해당 결과가 포함됩니다. 예를 들어 작업은 ExecutorService에 제출 된 Runnable 또는 Callable 인스턴스 일 수 있습니다 . 오퍼레이션 제출자는 오브젝트를 사용하여 오퍼레이션이 isDone () 인지 여부를 확인 하거나 블로킹 get () 메소드를 사용하여 완료 될 때까지 기다릴 있습니다.Future

예:

/**
* A task that sleeps for a second, then returns 1
**/
public static class MyCallable implements Callable<Integer> {

    @Override
    public Integer call() throws Exception {
        Thread.sleep(1000);
        return 1;
    }

}

public static void main(String[] args) throws Exception{
    ExecutorService exec = Executors.newSingleThreadExecutor();
    Future<Integer> f = exec.submit(new MyCallable());

    System.out.println(f.isDone()); //False

    System.out.println(f.get()); //Waits until the task is done, then prints 1
}

CompletableFutures

CompletableFutures 는 Java 8 (2014)에 도입되었습니다. 그것들은 사실 구아바 도서관의 일부인 구글의 리스너 러블 퓨처스 ( Google의 Listenable Futures) 에서 영감을 얻은 정기 선물의 진화입니다 . 그것들은 또한 당신이 체인으로 작업을 묶을 수있는 선물입니다. 그것들을 사용하여 일부 작업자 스레드에게 "일부 X 작업을 수행하고 완료되면 X 결과를 사용하여 다른 작업을 수행하십시오"라고 지시 할 수 있습니다. CompletableFutures를 사용하면 결과를 기다리는 스레드를 실제로 차단하지 않고도 작업 결과로 무언가를 수행 할 수 있습니다. 다음은 간단한 예입니다.

/**
* A supplier that sleeps for a second, and then returns one
**/
public static class MySupplier implements Supplier<Integer> {

    @Override
    public Integer get() {
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            //Do nothing
        }
        return 1;
    }
}

/**
* A (pure) function that adds one to a given Integer
**/
public static class PlusOne implements Function<Integer, Integer> {

    @Override
    public Integer apply(Integer x) {
        return x + 1;
    }
}

public static void main(String[] args) throws Exception {
    ExecutorService exec = Executors.newSingleThreadExecutor();
    CompletableFuture<Integer> f = CompletableFuture.supplyAsync(new MySupplier(), exec);
    System.out.println(f.isDone()); // False
    CompletableFuture<Integer> f2 = f.thenApply(new PlusOne());
    System.out.println(f2.get()); // Waits until the "calculation" is done, then prints 2
}

RxJava

RxJava is whole library for reactive programming created at Netflix. At a glance, it will appear to be similar to Java 8's streams. It is, except it's much more powerful.

Similarly to Futures, RxJava can be used to string together a bunch of synchronous or asynchronous actions to create a processing pipeline. Unlike Futures, which are single-use, RxJava works on streams of zero or more items. Including never-ending streams with an infinite number of items. It's also much more flexible and powerful thanks to an unbelievably rich set of operators.

Unlike Java 8's streams, RxJava also has a backpressure mechanism, which allows it to handle cases in which different parts of your processing pipeline operate in different threads, at different rates.

The downside of RxJava is that despite the solid documentation, it is a challenging library to learn due to the paradigm shift involved. Rx code can also be a nightmare to debug, especially if multiple threads are involved, and even worse - if backpressure is needed.

If you want to get into it, there's a whole page of various tutorials on the official website, plus the official documentation and Javadoc. You can also take a look at some of the videos such as this one which gives a brief intro into Rx and also talks about the differences between Rx and Futures.

Bonus: Java 9 Reactive Streams

Java 9's Reactive Streams aka Flow API are a set of Interfaces implemented by various reactive streams libraries such as RxJava 2, Akka Streams, and Vertx. They allow these reactive libraries to interconnect, while preserving the all important back-pressure.


I have been working with Rx Java since 0.9, now at 1.3.2 and soon migrating to 2.x I use this in a private project where I already work on for 8 years.

I wouldn't program without this library at all anymore. In the beginning I was skeptic but it is a complete other state of mind you need to create. Quiete difficult in the beginning. I sometimes was looking at the marbles for hours.. lol

It is just a matter of practice and really getting to know the flow (aka contract of observables and observer), once you get there, you'll hate to do it otherwise.

For me there is not really a downside on that library.

Use case: I have a monitor view that contains 9 gauges (cpu, mem, network, etc...). When starting up the view, the view subscribes itselfs to a system monitor class that returns an observable (interval) that contains all the data for the 9 meters. It will push each second a new result to the view (so not polling !!!). That observable uses a flatmap to simultaneously (async!) fetch data from 9 different sources and zips the result into a new model your view will get on the onNext().

How the hell you gonna do that with futures, completables etc ... Good luck ! :)

Rx Java solves many issues in programming for me and makes in a way a lot easier...

Advantages:

  • Statelss !!! (important thing to mention, most important maybe)
  • Thread management out of the box
  • Build sequences that have their own lifecycle
  • Everything are observables so chaining is easy
  • Less code to write
  • Single jar on classpath (very lightweight)
  • Highly concurrent
  • No callback hell anymore
  • Subscriber based (tight contract between consumer and producer)
  • Backpressure strategies (circuit breaker a like)
  • Splendid error handling and recovering
  • Very nice documentation (marbles <3)
  • Complete control
  • Many more ...

Disadvantages: - Hard to test

참고URL : https://stackoverflow.com/questions/35329845/difference-between-completablefuture-future-and-rxjavas-observable

반응형