Suppose I have an array of data, can 2 threads safely write to different indexes of the same array concurrently? I’m concerned about write speed, and I want to synchronize the ‘get index to write at’ bit vs the actual writing.
I am writing code that lets me assume 2 threads will not get the same index.
For two different indexes in an array the same rules apply as for two separate variables.
The Chapter “Threads and Locks” in the Java Language Specification starts by stating:
This means that you can safely write to two different indexes concurrently. However you need to synchronize a write/read to the same index if you want to make sure the consumer thread sees the last value written by the producer thread.