dimanche 26 avril 2020

In Java how to execute methods parallely while staying consistent using Java reflections?

Let's assume we have the following class:

public class Eval2 {
    Integer sumCount = 0;
    Integer mulCount = 0;
    public Integer sum(Integer a, Integer b) { sumCount++; return a + b; } 
    public Integer mul(Integer a, Integer b) { mulCount++; return a * b; } 
    public Integer results() {
        System.out.println("sums: " + sumCount + ", muls: " + mulCount);
        return 0;
    }
}

I have a list of type List<Pair<String, List<Integer>>, which contains which methods to execute, and the parameters, for example:

sum, [1, 2]
mul, [3, 4]
mul, [7, 9]
results, []

After I iterate through the list, and execute the methods using Java reflections, I get the following result, which is right:

3
12
63
sums: 1, muls: 2
0

But what if I want to execute these methods parallelly, while keeping it consistent? I made every method in Eval2 synchronized, and I did something like this in every iteration:

Thread t = new Thread() {
    public void run() {
        result[0] = (Integer) executedMethod.invoke(null, (Object[]) finalParametersArray);
        System.out.println(result[0]);
    };
t.start();

But, in this case, I can get the following result:

3
12
sums: 1, muls: 1
0
63

Which does not seem like it is consistent.

Finally, if I put t.join() after every t.start(), then it produces the right result, but then I guess it is not parallell, because every thread I make through the iterations does not start until the preceding thread executes. Thanks in advance.





Aucun commentaire:

Enregistrer un commentaire