i write the following code:
public void test() {
Callable<?> myCall = new Callable() {
@Override
public String call() throws Exception {
return doDomething();
}
};
Callable<?> myCall2 = new Callable() {
@Override
public String call() throws Exception {
return doDomething2();
}
};
ExecutorService executor = Executors.newFixedThreadPool(2);
List<Future<?>> futuresList = executor.invokeAll((Collection<? extends Callable<?>>) getList());
String result1 = futuresList.get(0).get();
String result2 = futuresList.get(0).get();
...
...
}
private List<Callable<?>> getList() {
.. create callables with wildcard and return them
}
i get the following compilation error: The method invokeAll(Collection>) in the type ExecutorService is not applicable for the arguments (Collection>).
EDIT
i added a method getList because i want this to use generics and not String.
I want to understand why it doesnt compile. and in my real program it is a method.
You have to understand when you need wildcards in generics. In your example, you don’t need them at all. You only need them when you don’t know the type of some generic object. In your example, you want the Callables to return Strings so you should use as your generic type, like this:
See Sun’s / Oracle’s tutorial on generics and wildcards
EDIT:
futuresList.get(0)tofuturesList.get(1)to get the second resultexecutor.shutdown()because people tend to forget this…EDIT2:
Responding to your comment, here is another example. That’s one way you could do stuff like this. I want to show how you have to generify all involved method from the caller all the way down inside your Callables or better your
doDomethingmethods.