Rus Paul Adrian Rus Paul Adrian - 4 years ago 319
Java Question

Java Multi-Thread Executor InvokeAll Problems

The code I'm having problems with is:

Executor executor = (Executor) callList;

List<ProgState> newProgList = executor.invokeAll(callList).stream()
.map(future -> {try {return future.get();} catch(Exception e){e.printStackTrace();}})
.filter(p -> p!=null).collect(Collectors.toList());



The method invokeAll(List>) is undefined for the type Executor


I am told I should use an executor like the one in the code snippet.

The Callables are defined within the following code:

List<Callable<ProgState>> callList = (List<Callable<ProgState>>) lst.stream()
.map(p -> ((Callable<ProgState>)(() -> {return p.oneStep();})))
.collect(Collectors.toList());


Here is the teacher's code:

//prepare the list of callables

List<Callable<PrgState>> callList = prgList.stream().map(p -> (() -> {return p.oneStep();})).collect(Collectors.toList());

//start the execution of the callables
//it returns the list of new created threads

List<PrgState> newPrgList = executor.invokeAll(callList).stream()
.map(future -> { try {
return future.get();
}
catch(Exception e) {

//here you can treat the possible
// exceptions thrown by statements
// execution

}
})
.filter(p -> p!=null).collect(Collectors.toList());


//add the new created threads to the list of existing threads

prgList.addAll(newPrgList);

Answer Source

You can't cast list of Callables with ExecutorService. You need to define ExecutorService which will inturn pick up callables and execute them in one or multiple threads in parallel.

This is what i think you are after:

ExecutorService executor = Executors.newCachedThreadPool();//change executor type as per your need.
List<ProgState> newProgList = executor.invokeAll(callList).stream().map(future -> {...
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download