Morrissss
Morrissss

Reputation: 324

Java - How to ensure visibility of array returned by a Callable thread

I need to calculate an array via a thread like this:

public class Calculator implements Callable<int[]> {
    @Override
    public int[] call() {
        int[] result = new int[100];
        for (int i = 0; i < result.length; i++) {
            result[i]++;
        }
        return result;
    }
}

And a main thread may look like this:

ExecutorService executor = Executors.newFixedThreadPool(1);
Future<int[]> future = executor.submit(new Calculator());
int[] result = future.get();

I cannot figure out how to ensure the visibility of all elements in result. According to the Memory Consistency Properties section, there seems to be no such happens-before relation.

One way to walk around is to wrap the array into an AtomicIntegerArray. But I wonder whether there is some other solution which can be generalized to any kind of primitive arrays.

Thanks

Upvotes: 3

Views: 188

Answers (1)

k5_
k5_

Reputation: 5568

From the javadoc of Future https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/Future.html

Memory consistency effects: Actions taken by the asynchronous computation happen-before actions following the corresponding Future.get() in another thread.

Upvotes: 4

Related Questions