Is it required to synchronize write access to an array in Java if each thread writes to a separate cell space?
EDIT: Specifically, the array is eith
You typically need to synchronize if you want other threads to be able to always see the last value you've written. But I could some cases where you'd be, say, precomputing a giganticly expensive long[] (where each entry would take a lot of CPU) and you'd be doing that from several threads, knowing no two of these threads shall write to the same cell. Then once all your threads would be done you'd be using synchronization once to be sure each subsequent read would see the correct values. Something like that.
Note that if you don't want to deal yourself with synchronization issues you may want to look into classes like AtomicLongArray. As an added benefit, classes like AtomicLongArray may be backed by an implementation that is impossible to re-create in 100% Java.
Similar question posed to the Concurrency Interest mailing list - "Atomic byte[] operations?".
David Holmes said:
Reading/writing different regions of the array should act like accessing independent arrays. This is what "no word-tearing" guarantees. No matter how the array is implemented by the VM the VM has to make sure this holds for basic array accesses.
As I said it is less clear if a native version of arraycopy gets involved.
If read access is also partitioned in the same manner, then synchronization is not needed as per bkail's link.
But if the threads read each other's writes, it would still be necessary to have a memory barrier to force synchronization of cache contents. Otherwise, threadys may get inconsistent read results.
In general, yes. Try Vector instead.