I have multiple threads accessing the elements from one shared array marked as final (I’ll never try to assign another array to it). Do I need to synchronize anything? Can I assume that the read/write to an element is atomic?
I have multiple threads accessing the elements from one shared array marked as final
Share
The writes are atomic unless the array is of type long or double. However, the atomic property won’t help you because the writes won’t be guaranteed to be visible to other threads.
If the array is of reference type, the problem is even worse because other threads may see your objects torn apart: some fields visible, some not.
To safely share a random-access collection of elements, you’ll need either a
synchronizedListwrapper around a plainArrayList, or a lock-freeCopyOnWriteArrayList.If you are OK with the fixed size of an array (and it would seem so), then also look into
AtomicReferenceArraysince it allows atomic compare-and-set and get-and-set operations, which may take you a step further in implementing what you need without the need for locks.