You will definitely have to use some sort of synchronization (either on your class or the underlying data structure) in order to ensure the data is left in a consistent state after method calls. Consider the following situations, with two Threads A and B, with the integer array initially containing all zero values.
- Thread A calls increment(0). The post-increment operation is not atomic; you can actually consider it to be broken down into at least three steps:
- Read the current value; Add one to the current value; Store the value.
- Thread B also calls increment(0). If this happens soon after Thread A has done the same, they will both read the same initial value for the element at index 0 of the array.
- At this point, both Thread A and B have read a value of '0' for the element they want to increment. Both will increment the value to '1' and store it back in the first element of the array.
- Thus, only the work of the Thread that last writes to the array is seen.
The situation is similar if you had a decrement()
method. If both increment()
and decrement()
were called at near-simultaneous times by two separate Threads, there is no telling what the outcome would be. The value would either be incremented by one or decremented by one, and the operations would not "cancel" each other out.
EDIT: Update to reflect Roman's (OP) comment below
Sorry, I mis-read the post. I think I understand your question, which is along the lines of:
"If I declare an array as volatile
,
does that mean access to its elements
are treated as volatile
as well?"
The quick answer is No: Please see this article for more information; the information in the previous answers here is also correct.