Parallelization of a function using for loop

david :

I have an integer array of values for which I have to calculate some number for every value. I am trying to parallelize this, e.g. I divide the array into a number of partitions and then calculate every partition in it's own thread. To do so I created a for loop that iterates over the partitions as follows:

    for (int i = 0; i < arrSplit.length; i++) {
        Thread t = new Thread(new Runnable() {  
            @Override
            public void run() {
                for (int j = arrSplit[i].startIndex; j < arrSplit[i].startIndex+arrSplit[i].length; j++) {
                    factors[j] = numPrimeFactors(values[j]);
                }
            }
        });
    }

The following two problems occurred to me:

  • "local variable defined in an enclosing scope must be final or effectively final" - I know that my variable "i" in "arrSplit[i]" is out of the scope, but I don't know of a way how to access it and don't quite understand why it is out of scope.
  • How can I join my threads? - If I would join each thread within the for loop I would effectively make the parallelization obsolete, because the next thread would only be started after the first one was already joined, right? So how can I go about this?
Andy Turner :

"local variable defined in an enclosing scope must be final or effectively final" 

It's not out of scope, it's saying that it's neither final (because it's not declared final) nor effectively final (because you increment it in the update part of the for loop).

You can declare final int ii = i; inside the outer loop, and use ii instead of i inside the runnable.

But actually, you don't seem to need i, other than to access arrSplit[i]. As such, it would be easier to use an enhanced for loop:

for (SplitType s : arrSplit) {
  // Use s in place of arrSplit[i].
}

How can I join my threads?

Put them into a list, and then call join on each element in turn after they have all been started.

But it might be easier to use something like parallel streams, so you don't have to manage the threads, or indeed the splits, yourself.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=19098&siteId=1