Reputation: 3248
I have created a threadpool in Java with the help of ExecutorService and List of Futures. I have created a RandomProcess class that implements Callable interface and overrides the call method to perform certain operations.
It looks like this:
public class RandomProcess implements Callable<Integer> {
private Result result;
public RandomProcess(Result result) {
super();
this.result = result;
}
@Override
public Integer call() throws Exception {
//performSomeOps returns a Result that has certain values that I need
result = performSomeOps();
return 1;
}
I have this Result object in this class that is supposed to reflect the changes that were made in the Randomprocess thread. unfortunately, the changes are not reflected when I return this Result.
public class Abc{
public Result check(){
Result result = new Result(true);
try {
ExecutorService exec = Executors.newFixedThreadPool(7);
List<Future<?>> futures = new ArrayList<Future<?>>(7);
for (Entity entity : randomListOfEntities) {
futures.add(exec.submit(new RandomProcess(result)));
}
for (Future<?> f : futures) {
f.get(); // wait for a process to complete
}
exec.shutdown();
}
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
}
Unable to figure out what the problem might be.
Upvotes: 0
Views: 101
Reputation: 2055
In Line result = performSomeOps(); you are not updating the value inside result that is being passed while submitting thread. You are just assigning new object at that line instead of changing the original object. You need to update the value inside result object(Something link result.setSomevalue() = performSomeOps().getSomeValue()) or pass your result object to performSomeOps(), and update result inside that method.
Upvotes: 1
Reputation: 2568
Need to Return "Result" as object from the "RandomProcess" Thread,Then Changes will be reflected.
public class RandomProcess implements Callable {
private Result result;
public RandomProcess(Result result) {
super();
this.result = result;
}
@Override
public Result call() throws Exception {
result = performSomeOps();
return result;
}
}
Upvotes: 0