Concurrently in Java 7 with result using non-final variables

I have something like:

int [] array1 = new int[20];
int [] array2 = new int[20];
int total= 0;
Random generator = new Random();

for(int i = 0; i < 10000; i++){
    int tmp = generator.nextInt(20);
    boolean win = custom_function(...);
    array1[tmp]++;
    array2[tmp]++
    total++;
}

// do something with the arrays

And I do not know how to implement it in parallel! When using designs such as

ExecutorService exec =
    Executors.newFixedThreadPool(SOME_NUM_OF_THREADS);
try {
    for (final Object o : list) {
        exec.submit(new Runnable() {
            @Override
            public void run() {
                // do stuff with o.
            }
        });
    }
} finally {
    exec.shutdown();
}

I just can't return or change anything, because it only works with final variables! How to act?


Each runnable must change the variables array1[tmp], array2[tmp]and array3[tmp]. Please note that this can be done through some kind of plug connection, I just don't know how to do it.

+4
source share
1 answer

It seems that you really want Callableone that calculates the result instead Runnable.

submit(Callable) Future, get .

import java.util.*;
import java.util.concurrent.*;

class Example {
    public static void main(String[] args) {
        final int n = 3;
        final int length = 20;

        ExecutorService ex = Executors.newFixedThreadPool(n);
        List<Future<int[]>> futures = new ArrayList<>();

        for (int i = 0; i < n; ++i) {
            futures.add(ex.submit(new Callable<int[]>() {
                Random r = new Random();

                @Override
                public int[] call() {
                    int[] result = new int[length];

                    for (int i = 0; i < length; ++i) {
                        int tmp = r.nextInt(length);
                        result[tmp]++;
                    }

                    return result;
                }
            }));
        }

        ex.shutdown();

        for (Future<int[]> f : futures) {
            try {
                System.out.println(Arrays.toString(f.get()));
            } catch (InterruptedException|ExecutionException e) {
                e.printStackTrace();
            }
        }
    }
}

:

[0, 1, 1, 1, 0, 1, 0, 2, 3, 1, 2, 0, 1, 2, 0, 2, 1, 2, 0, 0]
[2, 2, 1, 0, 0, 2, 1, 1, 3, 1, 2, 1, 0, 0, 1, 1, 0, 1, 1, 0]
[0, 1, 1, 1, 0, 1, 0, 4, 1, 2, 0, 1, 0, 1, 2, 2, 1, 0, 0, 2]
+1

All Articles