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.
The answer is no. Each array element has a region of memory reserved for it alone within the region attributed the overall array. Modifications of different elements therefore do not write to any of the same memory locations.
The simplest way to avoid problems with concurrency is to share only immutable data between threads. Immutable data is data which cannot be changed. To make a class immutable define the class and all its fields as final. Also ensure that no reference to fields escape during construction.
Unit of Concurrency Multitasking - Multiple tasks/processes running concurrently on a single CPU. The operating system executes these tasks by switching between them very frequently. The unit of concurrency, in this case, is a Process. Multithreading - Multiple parts of the same program running concurrently.
While Java isn't necessarily the best language for concurrency, there are a lot of tools, libraries, documentation and best practices out there to help. Using message passing and immutability instead of threads and shared state is considered the better approach to programming concurrent applications.
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:
17.4.1 Shared Variables
[...]
All instance fields, static fields and array elements are stored in heap memory. In this chapter, we use the term variable to refer to both fields and array elements.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With