Reputation: 5459
Consider 2 threads and an array int[] values
.
The first thread is performing:
synchronized (values) {
values[i] = 58;
}
while the second thread is performing:
if (values[i] == 58) {
}
outside a synchronized
block.
If the first thread first performs values[i]= 58
, is it guaranteed that if the second threads executes slightly later, that the if
of the second thread reads 58
even though the second thread reads values[i]
outside a synchronized
block?
Upvotes: 0
Views: 111
Reputation: 4365
Aforementioned behavior is not guaranteed. The guarantee of such a "visibility" is actually a subject of happens-before relationship:
The key to avoiding memory consistency errors is understanding the happens-before relationship. This relationship is simply a guarantee that memory writes by one specific statement are visible to another specific statement.
Happens-before relationship (according to JLS) can be achieved as such:
So, in your particular case, you actually need either synchronization using a shared monitor or AtomicIntegerArray in order to make access to the array thread-safe; volatile
modifier won't help as is, because it only affects the variable pointing to the array, not the array's elements (more detailed explanation).
Upvotes: 1
Reputation: 78995
If the first thread first performs values[i]= 58, is it guaranteed that if the second threads executes slightly later, that the if of the second thread reads 58 even though the second thread reads values[i] outside a synchronized block?
No
Synchronising this way does not stop other threads to perform any operation on the array simultaneously. However, other threads will be prevented to grab a lock on the array.
Upvotes: 2