I want to perform parallel calculation for several sets of input values. Do I need to synchronize the calculate(a, b, inputIndex)
method?
private static final String FORMULA = "(#{a} + #{b}) * (#{a} + #{b} * #{b} - #{a})";
private List<Pair<Integer, Integer>> input = Arrays.asList(
new ImmutablePair<>(1, 2),
new ImmutablePair<>(2, 2),
new ImmutablePair<>(3, 1),
new ImmutablePair<>(4, 2),
new ImmutablePair<>(1, 5)
);
private List<String> output = new ArrayList<>(Arrays.asList("", "", "", "", ""));
public void calculate() {
IntStream.range(0, input.size()).forEach(idx -> {
Pair<Integer, Integer> pair = input.get(idx);
Thread threadWrapper = new Thread(
() -> this.calculate(pair.getLeft(), pair.getRight(), idx)
);
threadWrapper.start();
});
try {
Thread.sleep(4000); // waiting for threads to finish execution just in case
System.out.println("Calculation result => " + output);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
private void calculate(Integer a, Integer b, int inputIndex) {
System.out.println("Thread with index " + inputIndex + " started calculation.");
Evaluator eval = new Evaluator();
eval.putVariable("a", a.toString());
eval.putVariable("b", b.toString());
try {
String result = eval.evaluate(FORMULA);
Thread.sleep(3000);
output.set(inputIndex, result);
System.out.println("Thread with index " + inputIndex + " done.");
} catch (EvaluationException | InterruptedException e) {
e.printStackTrace();
}
}
Because if the code of calculate
method was inside run
method of Runnable
I wouldn't need to do that. (also I think I don't need synchronized collections there because for input
I only get data by index and for output
I put element into the certain position)