Are there any concurrency problems with one thread reading from one index of an array, while another thread writes to another index of the array, as long as the indices are different?
e.g. (this example not necessarily recommended for real use, only to illustrate my point)
class Test1 { static final private int N = 4096; final private int[] x = new int[N]; final private AtomicInteger nwritten = new AtomicInteger(0); // invariant: // all values x[i] where 0 <= i < nwritten.get() are immutable // read() is not synchronized since we want it to be fast int read(int index) { if (index >= nwritten.get()) throw new IllegalArgumentException(); return x[index]; } // write() is synchronized to handle multiple writers // (using compare-and-set techniques to avoid blocking algorithms // is nontrivial) synchronized void write(int x_i) { int index = nwriting.get(); if (index >= N) throw SomeExceptionThatIndicatesArrayIsFull(); x[index] = x_i; // from this point forward, x[index] is fixed in stone nwriting.set(index+1); } }
edit: critiquing this example is not my question, I literally just want to know if array access to one index, concurrently to access of another index, poses concurrency problems, couldn't think of a simple example.
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.
A [portion of code] is thread-safe if it behaves correctly when accessed from multiple threads, regardless of the scheduling or interleaving of the execution of those threads by the runtime environment, and with no additional synchronization or other coordination on the part of the calling code.
A string is immutable and therefore thread safe.
While you will not get an invalid state by changing arrays as you mention, you will have the same problem that happens when two threads are viewing a non volatile integer without synchronization (see the section in the Java Tutorial on Memory Consistency Errors). Basically, the problem is that Thread 1 may write a value in space i, but there is no guarantee when (or if) Thread 2 will see the change.
The class java.util.concurrent.atomic.AtomicIntegerArray
does what you want to do.
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