Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java concurrency - writing to different indexes of the same array

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.

like image 296
John Hinnegan Avatar asked Jan 23 '12 20:01

John Hinnegan


People also ask

Can multiple threads write to the same array?

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.

How do you solve concurrency problems in Java?

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.

What is the difference between multi threading and concurrency?

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.

Is Java good for concurrency?

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.


1 Answers

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.

like image 100
aioobe Avatar answered Oct 24 '22 15:10

aioobe