简体   繁体   中英

Are simultaneous reads from an array thread-safe?

I have an array which contains integer values declared like this:

int data[] = new int[n];

Each value needs to be processed and I am splitting the work into pieces so that it can be processed by separate threads. The array will not be modified during processing.

Can all the processing threads read separate parts of the array concurrently? Or do I have to use a lock?

In other words: is this work order thread-safe?

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]

Reading contents of an array (or any other collection, fields of an object, etc.) by multiple threads is thread-safe provided that the data is not modified in the meantime.

If you fill the array with data to process and pass it to different threads for reading, then the data will be properly read and no data race will be possible.

Note that this will only work if you create the threads after you have filled the array . If you pass the array for processing to some already existing threads without synchronization, the contents of the array may not be read correctly. In such case the method in which the thread obtains the reference to the array should be synchronized, because a synchronized block forces memory update between threads.

On a side note: using an immutable collection may be a good idea. That way you ensure no modification is even possible. I would sugges using such wrapper. Check the java.util.concurrent.atomic package, there should be something you can use.

只要线程不修改数组中的内容,就可以从多个线程中读取数组。

If you ensure all the threads are just reading, its thread safe. Though you should not be relying on that fact alone and try to make your array immutable via a wrapper.

Sure, if you just want to read it, pass the array to the threads when you create them. There won't be any problem as long as you don't modify it.

从数组数组中读取是线程安全操作,但如果您要修改数组而不是考虑使用类AtomicIntegerArray

Consider populating a ConcurrendLinkedQueue and have each thread pull from it. This would ensure that there are no concurrency issues.

Your threads would each be pulling their data from the top of the queue and processing it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM