shiv455 shiv455 - 2 months ago 10
Java Question

Difference between completableFuture,Future and Observable Rxjava

would like to know the difference between
CompletableFuture,Future and Observable RxJava..

What i know is all are asynchronous but

Future.get() blocks the thread

CompletableFuture gives the callback methods

RxJava Observable ---similar to CompletableFuture with other benefits(not sure)

For ex:
if client needs to make multiple service calls and when we use Futures (Java) Future.get() will be executed sequentially...would like to know how its better in RxJava..

And the documentation http://reactivex.io/intro.html says

It is difficult to use Futures to optimally compose conditional asynchronous execution flows (or impossible, since latencies of each request vary at runtime). This can be done, of course, but it quickly becomes complicated (and thus error-prone) or it prematurely blocks on Future.get(), which eliminates the benefit of asynchronous execution.

really interested to know how RxJava solves this problem...i found it difficult to understand from the documentation..Please help!!

Answer

Futures

Futures were introduced in Java 5. They are objects that promise to hold the result of something that (maybe) hasn't occurred yet. They are created, for example, when a task (i.e Runnable or Callable) are submitted to an executor. The caller can use the the future to check whether the task isDone(), or wait for it to finish using get(). Example:

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 "calculation" is done, then prints 1
}

CompletableFutures

CompletableFutures were introduced in Java 8, and are in fact an evolution of regular Futures inspired by Google's Listenable Futures. They are Futures that also allow you to string tasks together in a chain. You can use them to tell some worker thread to "go do some task X, and when you're done, go do this other thing based on the result of X". Here's a simple example:

public static class MySupplier implements Supplier<Integer> {

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

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. Its main advantage over futures is that it works on streams of zero or more items including never-ending streams with an infinite number of items. It can do so asynchronously and with little or no thread blocking. Futures, on the other hand, handle one item at a time, and for each item each future has to be checked for completeness and/or waited for.

RxJava has a very rich collection of operators, and is extremely flexible. Also, unlike Java's "native" streams, it can handle "Push" streams (i.e. streams of data that you cannot control or rate limit - such as readings from a sensor, or a stream of user requests). The downside of Rx is that despite the pretty good documentation, it's 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. 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.