Java数组:+原子*同步,或同步就足够了? [英] Java arrays: synchronized + Atomic*, or synchronized suffices?

查看:243
本文介绍了Java数组:+原子*同步,或同步就足够了?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个问题已经被一次又一次地问过,但我还有一个疑问。当人们说同步创建了一个内存屏障,这是什么内存屏障申请,任何缓存的变量?这看起来不像是可行的。

This question has been asked again and again, but I have still a doubt. When people say that synchronized creates a memory barrier, what does this memory barrier apply to, ANY cached variable? This doesn't look like feasible.

因此​​,由于这种疑问,我已经写了一些code,看起来像这样:

So, due to this doubt, I have written some code that looks like this:

final AtomicReferenceArray<Double> total=new AtomicReferenceArray<Double>(func.outDim);
for(int i=0; i<func.outDim; i++) total.set(i, 0.);
for(int i=0; i<threads; i++){
    workers[i]=new Thread(new Runnable(){
        public void run() {
            double[] myPartialSum=new double(func.outDim);
            //some lengthy math which fills myPartialSum...

            //The Atomic* guarantees that I'm not writing local copies of the Double references (whose value are immutables, so it's like an array of truly volatile doubles) in variable total, synchronized(total) atomizes the sum
            synchronized(total){ for(int i=0; i<func.outDim; i++) total.set(i, total.get(i)+myPartialSum[i]); }
        };
    workers[i].start();
}
//wait for workers to terminate...

//print results accessing total outside of a synchronized(total) block, since no worker is alive at this point.

我不知道是否有可能刚刚替补总的类型有普通的双[]:这将需要同步的(总)(在run()方法)保证,我不是每次的本地副本工作双打的数组中的索引,也就是内存围栏并不只适用于本身(这是引擎盖指针下)的值,但对指数的太。这是否会发生?

I wonder if it's possible to just substitute the type of total with a plain double[]: this would require that synchronized(total) (in the run() method) assures that I'm not working with local copies of each index in the array of doubles, that is, the memory fence does not apply only to the value of total itself (which is under the hood a pointer), but to the indexes of total too. Does this happen?

推荐答案

内存屏障适用于所有内存引用,即使是无关的内容。当您同步,你会看到一个到任何内存值的最新副本,当你离开块,另外还有一个内存屏障。

The memory barrier applies to all memory references, even unrelated ones. When you synchronize total you will see an up to date copy of any memory values and when you leave the block, there is another memory barrier.

这篇关于Java数组:+原子*同步,或同步就足够了?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆