I am looking at the following code (someone else's code) and part of the code seems obscure to me:
List<string> result = forkJoinPool.invokeAll(tasks)
.stream()
.map(MUtil.rethrowFunction(Future::get))
.collect(toList());
This part is straightforward, a ForkJoinPool.invokeAll() returning a List of Future objects and further processing returns a List of Strings.
Later, the list.stream().map() uses a static method on Mutil class Mutil.rethrowFunction(Future::get) and passes it an object of Future type. Looking at the Mutil source code :
public class Mutil {
public static <T, R> Function<T, R> rethrowFunction(WithExceptionsIF<T, R> function) {
return t -> {
try { return function.apply(t); }
catch (Exception exception) { throwAsUnchecked(exception); return null; }
};
}
@FunctionalInterface
public interface WithExceptionsIF<T, R> {
R apply(T t) throws Exception;
}
@SuppressWarnings ("unchecked")
private static <E extends Throwable> void throwAsUnchecked(Exception exception) throws E { throw (E)exception; }
}
Here are my questions, as I am learning Generics, lambda and java.util.function package:
The signature of
Mutil.rethrowFunction()
, says it returns<T, R> Function<T, R>
and uses a parameter of typeWithExceptionsIF<T, R>
(which is a functional interface). How does Future.get() translates into theMutil.rethroFunction()
signature? Future.get(), returns a computed result and not a Function?How does
Future.get()
, which is passed toMutil.rethrowFunction()
translates toWithExceptionIF<T,R>
type?t->{return function.apply(t);}
what is going on in this statement? is 't' the Future object, if so then who is the "function"?The signature of
Mutil.throwAsUnchecked(Exception exception)
method has<E extends Throwable>
defined after the keyword "static". If "exception" is the only parameter passed to the method, where does the E come from and why is it declared before the method's return type (void)?
Thanks for any clarity.