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?
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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With