I need some tasks to be done multi threaded.
I know in advance that i will continue with my program when all tasks are completed.
Is the following code right for this purpose?
public void test() {
Callable<String> myCall = new Callable() {
@Override
public String call() throws Exception {
return doDomething();
}
};
Callable<String> myCall2 = new Callable() {
@Override
public String call() throws Exception {
return doDomething2();
}
};
ExecutorService executor = Executors.newFixedThreadPool(2);
List<Callable<String>> list = Arrays.asList(myCall,myCall2);
List<Future<String>> futuresList = executor.invokeAll(list);
String result1 = futuresList.get(0).get();
String result2 = futuresList.get(0).get();
//...
}
I’m trying to change this to work with generics:
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<Callable<?>> list = Arrays.asList(myCall,myCall2);
List<Future<?>> futuresList = executor.invokeAll((Collection<? extends Callable<?>>)list);
String result1 = futuresList.get(0).get();
String result2 = futuresList.get(0).get();
// ...
}
I get the following compilation error:
The method
invokeAll(Collection<? extends Callable<T>>)in the type ExecutorService is not applicable for the arguments(Collection<capture#2-of ? extends Callable<?>>).
Aside from you accessing the zeroth index twice I dont see anything wrong with it.
This edit is in regards to your question on how to implement it without the ExecutorService. As ColinD notes, you really shouldn’t I will show why
To get the same set of functionality you would need two Objects and use two threads as a latch
Now what if you want to add another thread/unit-of-work then you need
And so forth. Hence your solution is the better way to do this.