I came across code that used Callable
instead of Supplier
. I did not see any threads spawning across to use Callable
. But is it okay to use Callable
instead of Supplier
?.
One of the devs I work with stated that it does the same job. Going by the docs it doesn't but would like to know experts opinions here.
Callable<Optional<NodePermissionResponse>> successHandler = () -> {
NodePermissionResponse restResponse = response.readEntity(NodePermissionResponse.class);
return Optional.of(restResponse);
};
Callable<Optional<NodePermissionResponse>> errorHandler = () -> {
ApplicationResponse appResponse = response.readEntity(ApplicationResponse.class);
if(appResponse.getError().getStatusCode() == NOT_FOUND_STATUS_CODE) {
return Optional.empty();
}
log.error("Fetching entitlements for group failed", appResponse.getError());
throw new ApplicationAccessException(appResponse.getError());
};
return processResponse(
successHandler, errorHandler, response);
}
Method to process response
public static <T> T processResponse(Callable<T> successfulResponseHandler,
Callable<T> unsuccesfulResponseHandler,
Response response) {
//do the job here
}
I did not see any threads spawning across to use Callable. But is it okay to use Callable instead of Supplier.
As mentioned in the comments already both Callable
and Supplier
are interfaces which have the same function descriptor i.e. their SAM (Single Abstract Method) are same in their signatures.
One difference being that, Callable#call
is able to throw checked exceptions, on the other hand Supplier#get
is not.
This means for your use case using any of them is completely acceptable, although as mentioned in this answer
Though both interfaces will suffice in this specific case they're intended for different purposes i.e. A Callable is "A task that returns a result" while a Supplier is "a supplier of results". The latter is more "general" in as opposed to the former.
So, the conclusion is to go with the one that most suits your specific scenario.