Writes link types (i.e. Object ) and types of word size values (i.e. int in a 32-bit system) are atomic. This means that when you look at the values (position 6), you can be sure that you will either get the old value or the new value, but not something else (if you have a type such as a large structure that it can spliced, and you can read the meaning when it was halfway written). You do not need lock or volatile if you are ready to accept the potential risk of reading obsolete values.
Please note that since memory protection is not introduced at this moment (a lock or using volatile and add one), it is possible that the variable was updated in another thread, but the current thread is not enforcing these changes; it can read the "obsolete" value (potentially) some time after changing it in another thread. Using volatile ensures that the current thread is more likely to observe changes in the variable.
You can be sure that after calling WaitAll you will have the corresponding value, even without lock or volatile .
Also note that although you can be sure that the link to the reference type is written atomically, your program makes no guarantees regarding the observed order of any changes to the actual object referenced by the link. Even if, from the point of view of the background thread, the object is initialized before it is assigned to the instance field, this may not happen in that order. Thus, another thread can observe the record of the reference object, but then follow this link and find the object in the initialized or partially initialized state. The introduction of a memory barrier (i.e., using the variable volatile can potentially allow you to avoid performing such reorders, thereby ensuring that this does not happen. That is why it is better to simply not do this in the first place , and simply to let the two tasks return results that they generate, not manipulate, a private variable.
WaitAll will introduce a memory barrier, in addition to the fact that both tasks will actually be completed, which means that you know that the variables are relevant and do not have old obsolete values.
Servy source share