【发布时间】:2016-09-23 10:46:49
【问题描述】:
在 Java 中,如果多个线程异步写入原始(双)数组的不同部分,并且(仅)主线程在所有线程完成写入后从数组中读取。
- 是否存在可见性问题,即有可能读取或写入原始数组的线程本地版本?
- 如果 1. 为真,是否可以通过在读取主线程之前添加内存屏障来解决?您会建议使用哪一种?
下面的示例代码。
提前非常感谢, 曼努埃尔
//Example code to calculate distance of 1 point to 1mln other points:
double[][] history = this.createRandomMatrix(1000000,8);
double[] order = this.createRandomMatrix(1,8)[0];
double[] result = new double[1000000];
for(int i = 0; i< 100;i++){
pool.execute(new Calculator(history, newPoint, result,i*10000,10000 + i * 10000));
}
pool.shutdown();
try {
pool.awaitTermination(1, TimeUnit.SECONDS);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//read happens here
//Calculator run function
public void run() {
for(int i = start;i<end;i++){
result[i] = this.computeDistance(history[i],order);
}
}
【问题讨论】:
标签: java concurrency visibility