What's the use of generic in Callable interface?
Consider this code which I copied from https://blogs.oracle.com/CoreJavaTechTips/entry/get_netbeans_6:
import java.util.\*;
import java.util.concurrent.\*;
public class CallableExample {
public static class WordLengthCallable
implements Callable {
private String word;
public WordLengthCallable(String word) {
this.word = word;
}
public Integer call() {
return Integer.valueOf(word.length());
}
}
public static void main(String args[]) throws Exception {
ExecutorService pool = Executors.newFixedThreadPool(3);
Set<Future<Integer>> set = new HashSet<Future<Integer>>();
for (String word: args) {
Callable<Integer> callable = new WordLengthCallable(word);
Future<Integer> future = pool.submit(callable);
set.add(future);
}
int sum = 0;
for (Future<Integer> future : set) {
sum += future.get();
}
System.out.printf("The sum of lengths is %s%n", sum);
System.exit(sum);
}
}
Integer in Callable<Integer> and Future<Integer> is not being used. It could be anything else as well like Callable<String> and Future<String> and code will still work.
I understand usage of Generics and appreciates its usage specially in collections.
Thanks.
The point of Callable vs Runnable is the ability in Callable to return a value (retrievable via Future if using an ExecutorService). They could have coded it to just return Object and make the code cast but then there would be absolutely no compile-time checking. Seems logical to make Callable generic to specify the return type so that you don't need the explicit cast and you have compile-time checking.
Of course, due to type-erasure this all goes away at run-time but that does not reduce its value WRT intent and compile-time.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With