Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>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.</p> <ul> <li>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: <ul> <li>Read the current value; Add one to the current value; Store the value.</li> </ul></li> <li>Thread B also calls increment(0). If this happens soon after Thread A has done the same, they will both read the <em>same initial value</em> for the element at index 0 of the array. </li> <li>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.</li> <li>Thus, only the work of the Thread that <em>last writes</em> to the array is seen.</li> </ul> <p>The situation is similar if you had a <code>decrement()</code> method. If both <code>increment()</code> and <code>decrement()</code> 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.</p> <p><strong>EDIT: Update to reflect Roman's (OP) comment below</strong></p> <p>Sorry, I mis-read the post. I think I understand your question, which is along the lines of:</p> <blockquote> <p>"If I declare an array as <code>volatile</code>, does that mean access to its elements are treated as <code>volatile</code> as well?"</p> </blockquote> <p>The quick answer is No: Please see <a href="http://www.javamex.com/tutorials/volatile_arrays.shtml" rel="nofollow noreferrer">this article for more information</a>; the information in the previous answers here is also correct.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload