6

I have an array of arrays of int.

DataArray[X][Y]

I would like to create a thread for each X, which iterates along Y. I cannot figure out how to pass the appropriate X value to each thread.

essentially i would like to be able to do

ExecutorService threadPool = Executors.newFixedThreadPool(10);
for (int i = 0; i < X; i++) {
  threadPool.submit(new Runnable() {
    public void run() {         
      Function_to_run(i);
    }
  });
}

Any help would be appreciated

Chetan Kinger
  • 15,069
  • 6
  • 45
  • 82
cpri
  • 421
  • 4
  • 12

2 Answers2

8

Only final values can be captured within a method-local-anonymous-inner-class. You need to change your code as follows :

for (int i = 0; i < X; i++) {
        final int index = i;
        threadPool.submit(new Runnable() {
             public void run() {

                  Function_to_run(index);

         }
     });
Chetan Kinger
  • 15,069
  • 6
  • 45
  • 82
  • This seems to have worked; will give it some testing – cpri May 17 '15 at 15:14
  • @user1908455 Alright. Let me know if it didn't work. If it did work, don't forget to tick and upvote :) – Chetan Kinger May 17 '15 at 15:16
  • Why does this work? Shouldn't the `final` variable within the loop raise an exception on the 2nd iteration? You can't assign a new value to a `final` variable that's already initialized. The variable `index` does not go out of scope. – scottb May 18 '15 at 07:15
  • @scottb a new `index` variable is created for each iteration of the loop. The scope of `index` is limited to an iteration. – Chetan Kinger May 18 '15 at 07:18
  • @ChetanKinger: I believe you, but I don't understand why. Does the for loop create a new stack each time it iterates? If not, I don't see where `index` would fall out of scope. – scottb May 18 '15 at 07:19
  • @scottb I am not sure what happens internally but what I am sure of is that the effect is the same as calling a method recursively. – Chetan Kinger Jun 25 '15 at 09:12
  • @ChetanKinger: Perhaps so, although I am not aware that any JVM presently supports tail-recursion. Without such support, are you then suggesting that each iteration loads a new stack frame? Of course it can't, because loops with a large number of iterations are not known to cause stack overflow exceptions. – scottb Jul 01 '15 at 00:34
0

Any local variable, formal method parameter or exception handler parameter used but not declared in an inner class must be declared final. Any local variable, used but not declared in an inner class must be definitely assigned before the body of the inner class.

Sunil Kumar
  • 5,477
  • 4
  • 31
  • 38