Are Java arrays: synchronized + Atomic * or synchronized?

This question has been asked again and again, but I still doubt it. When people say that synchronized creates a memory barrier, what does this memory barrier refer to, ANY cached variable? It does not look doable.

So, because of this doubt, I wrote 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 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. 

I wonder if it is possible to simply substitute the type total with a simple double []: this will require that the synchronized (common) (in the run () method) ensures that I do not work with local copies of each index in the doubles array, i.e. memory sampling does not apply only to the total value itself (located under the hood of the pointer), but also to the total indices. It happens?

+3
source share
2 answers

The memory limit applies to all memory references, not even related to them. When you synchronize total , you will see an updated copy of any memory values, and when you leave the block, there is another memory barrier.

+4
source

If my understanding is correct, synchronized(total) will synchronize any access to total and, therefore, should synchronize access (read and write) to the values ​​in the array too.

Since the double array directly contains values ​​instead of references, they should not be accessible by other threads during execution of the synchronized block. If you have an array of objects, you cannot change the links in the array, but you can still access the objects themselves.

0
source

All Articles