Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Futures.transform, what is the difference between using a Function and an AsyncFunction

I know that the apply method of Function returns an object synchronously, and the apply of AsyncFunction runs asynchronously and returns a Future.

Can you give me an example of when to prefer what.

One code snippet that I saw looked something like this:

Futures.transform(someFuture, new AsyncFunction<A, B>() {
  public B apply(A a) {
    if (a != null) {
      return Futures.immediateFuture(a.getData())
    } else {
      return Futures.immediateFailedFuture(checkException(());
    }
  });
});

Since the value inside AsyncFunction is returned as immediate result, why is AsyncFunction needed here? Or is this just a bad example that I came across?

like image 722
SherinThomas Avatar asked Jun 05 '14 00:06

SherinThomas


2 Answers

Using AsyncFunction makes sense here. If you want to throw some checked exception out of the apply() method in Function, it would complain it's not handled. You can not throw it out of the apply() for it's overridden. So If you want to throw some checked exception, AsyncFunction should be a valid solution. For those saying the given example is bad and given Function example, can you please try compile it?

like image 162
Tristan.Liu Avatar answered Oct 22 '22 03:10

Tristan.Liu


Since the value inside AsyncFunction is returned as immediate result, why is AsyncFunction needed here? Or is this just a bad example that I came across?

Careful. That piece of code is generating an instance of an anonymous class and passing that instance to the transform method. The transform method will use the AsyncFunction is a separate thread. The Future returned chains to retrieve the results from the AsyncFunction and return the result of that Future. This code still involves asynchronous processing.

Use asynchronous processing when you want to and can continue doing work while something else is being executed.

like image 27
Sotirios Delimanolis Avatar answered Oct 22 '22 05:10

Sotirios Delimanolis