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
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.