What is the difference between an object of a Void type and that of an unbounded wildcard type in Java generics? I mean I understand the use of <?>, and also the use of Void in terms of reflection, but I was a bit intrigued when I saw the Java source code for
java.util.concurrent.AbstractExecutorService
and its method
public Future<?> submit(Runnable task) {
...
RunnableFuture<Void> ftask = new TaskFor(task, null);
...
return ftask;
where inside the method it uses a RunnableFuture<Void> instead of RunnableFuture<?>
can someone help me understand the reason behind this? Thanks
Void is a special class that is used to represent no return value. While there is nothing special about
Voidper se, it can’t be (and never is) instantiated, so the only possible value for it is alwaysnull. It is used for two things:voidreturn type in Java reflection usingVoid.TYPE. See How to determine by reflection if a Method returns 'void' for example.So it is very different from a wildcard, which is no actual class but represents one specific, unknown type at compile time. At runtime, it is erased like every other generic type.
Regarding the
submitmethod. Here are the two implementations from JDK 6:and JDK 7:
As you can see, the type was changed to
Voidonly in JDK 7, probably because it makes more sense conceptually. But since the interface of the method could not be changed (for compatibility reasons and because the method implementsFuture<?> submit(Runnable task)of the ExecutorService interface), the return typeFuture<?>stayed the same. That’s my explanation.