Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what does first <T> in "<T> Future<T> submit(Callable<T> task)" stands for?

I'm new to Java and is trying to learn the concept of return type. I was reading Java API for the interface ExecutorService:

enter image description here

I know for submit(Callable<T> task), it returns a Future object of T type, however, there is another <T> in front of Future<T>, what does it represent?

like image 660
Thor Avatar asked Oct 17 '25 03:10

Thor


2 Answers

The leading <T> is defining T as a type parameter (aka generics), in simple words, the function uses a generic type parameter called T where T is a type (at the time of writing this (Java 1.8), only reference types are supported)

<T> void fn(T t); // T is a type parameter

For example, Integer could be concrete type

<Integer>fn(1);

The compiler can often infer the type as follows

fn(1)

In your example, submitting a Callable<Integer> returns a Future<Integer>

Future<Integer> future = executor.submit(callableInteger);
Integer futureResult = future.get(); //type-saftey powered by generics 

You can check this out for a detailed explanation.

like image 81
Sleiman Jneidi Avatar answered Oct 18 '25 17:10

Sleiman Jneidi


It's declaring a type variable that has scope only for the submit() method.

An Executor is not generic, but some of its methods use generic types, which are declared between the method modifiers and the return type.

like image 39
erickson Avatar answered Oct 18 '25 16:10

erickson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!