Note that there are some explanatory texts on larger screens.

plurals
  1. POJava arrays: synchronized + Atomic*, or synchronized suffices?
    primarykey
    data
    text
    <p>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.</p> <p>So, due to this doubt, I have written some code that looks like this:</p> <pre><code>final AtomicReferenceArray&lt;Double&gt; total=new AtomicReferenceArray&lt;Double&gt;(func.outDim); for(int i=0; i&lt;func.outDim; i++) total.set(i, 0.); for(int i=0; i&lt;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&lt;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. </code></pre> <p>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 <code>total</code> itself (which is under the hood a pointer), but to the indexes of <code>total</code> too. Does this happen?</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload