Are thread-safe reads from the array at the same time?

I have an array that contains integer values ​​declared as follows:

int data[] = new int[n]; 

Each value needs to be processed, and I break the product into parts so that it can be processed in separate streams. The array will not be modified during processing.

Can all processes process separate parts of an array at the same time? Or do I need to use a lock?

In other words: is this working order unsafe?

 Array is created and filled Threads are created and started Thread 0 reads data[0..3] Thread 1 reads data[4..7] Thread 2 reads data[8..n] 
+8
java arrays multithreading
source share
6 answers

Reading the contents of an array (or any other collection, object fields, etc.) by multiple threads is thread safe, provided that the data does not change at the same time.

If you fill the array with data for processing and pass them to different threads for reading, then the data will be read correctly, and no data race will be possible.

Note that this will only work if you create threads after filling the array . If you pass the array for processing to existing threads without synchronization, the contents of the array may not be read correctly. In this case, the method in which the thread receives a reference to the array must be synchronized, since the synchronized block forcibly updates the memory between the threads.

On the other hand: using an immutable collection may be a good idea. Thus, you guarantee that no modification will be possible. I would rather use such a wrapper. Check out the java.util.concurrent.atomic package, there should be something you can use.

+6
source share

As long as the threads do not modify the contents of the array, it is fine to read the array from multiple threads.

+2
source share

If you make sure that all threads are just reading, streaming security. Although you should not rely on this fact alone and try to make your array immutable through the shell.

0
source share

Of course, if you just want to read it, pass the array to the threads when you create them. There will be no problems if you do not change .

0
source share

Reading from an array is an operation that optimizes the stream, but if you are modifying an array, consider using the AtomicIntegerArray class.

0
source share

Consider populating a ConcurrendLinkedQueue and extracting each thread from it. This will ensure no concurrency issues.

Your threads will retrieve data from the top of the queue and process it.

0
source share

All Articles