I'm wondering why do I get warning message when I am trying to return Future object with generic wildcard, or maybe I dont have to worry about it at all?
My code:
public static Future<?> getExecutableFutureTask(Callable<?> task, AsyncTaskExecutor executor) {
return executor.submit(() -> {
try {
task.call();
} catch (Exception e) {
throw new RuntimeException(e);
}
});
}
Sonar tries to force me to not use generic wildcard, even though AsyncTaskExecutor.submit method returns Future<?> object.
Can someone tell me why I've got this warning message?
even though AsyncTaskExecutor.submit method returns Future<?> object.
No it doesn't. it returns a Future<T>
where the T is from what you submit to it. The way you've set up your signature, sure, that ?
here. But that's your own doing.
What sonar wants you to write, is this:
public static <T> Future<T> getExecutableFutureTask(Callable<T> task, AsyncTaskExecutor executor) {
return executor.submit(() -> {
try {
return task.call();
} catch (Exception e) {
throw new RuntimeException(e);
}
});
}
In other words, the executor 'framework' lets you 'link' the type of the provided Callable to the type of the Future it makes for you, and sonar wants you to maintain that link. There is no harm in doing this, and it might be useful for some users of your getExecutableFutureTask
.
I'm not sure why this method is useful, though.