Javamex

Java discussion forum to accompany the Javamex web site.

You are writing on this page that :
"declaring an array volatile does not give volatile access to its fields"
and also
it is unsafe to call arr[x] = y on an array (even if declared volatile) in one thread and then expect arr[x] to return y from another thread

if I have such an class :

public class Test {

int[] numbers = new int[Integer.MAX_VALUE];

void increment(int ind){
numbers[ind]++;
}

int get(int ind){
return numbers[ind];
}
}

and some reader threads , "get" and only one writer "increment".
I though not require further synchronization in this class in a case of MRSW.
But you claim that the elements inside the array could be cached. Is this right ?

Thanks

Views: 231

Reply to This

Replies to This Discussion

With a volatile array, the "volatile" characteristic applie sto the reference, not individual elements in the array.

So if you want accesses to elements to be thread-safe, you generally need to synchronize on accesses in some other way.

The easiest way is to use one of the atomic array classes.
Studying the description of volatile in the Java language spec you absolutely get the impression that "volatile" only apply to a single primitive value (int, boolean etc) and a pointer is of course a special case of this. From this one can assume that volatile on an array ONLY protects reading / updating the array pointer and nothing else!

Reply to Discussion

RSS

© 2024   Created by Neil Coffey.   Powered by

Badges  |  Report an Issue  |  Terms of Service