Here is a class field,
class someClass {
Int someClassField = nil
...
(please, please(!) ignore issues of visibility, this question is concerned wih overall design, not language implementation) If I look online at tutorials, I am told this field is safe to use by multiple threads. When the tutorials say safe, they do not mean that one thread can not interfere with the value visible to another. Such interference may be the intention - the field may be a counter. What the tutorials mean is, when one thread changes this field, the field will not be left in an unsafe state. Take this field,
class someClass {
List<List> someClassField = new List<Int>()
...
As I understand, if the field is a simple list, one thread could leave it in an inconsistent state (i.e. partially disconnected). If another thread uses the list it will fail - in a language like C this would be a disaster. Even reading could fail.
Well then, the class used on the field could be asked to copy out it's state (the copying could be extended to a full defence of immutability, but I'm keeping the discussion simple). If the class copies out it's state, then modifications are done away from the copy on the field, in a new copy modified for return. This new, modified copy can be reassigned to the field. But is that assignment threadsafe - in the sense that the value of the field can not be in an inconsistent state - because the allocation of the reference of the new object to the field is atomic?
I'm ignoring all issues of wether a language engine might reorder, cache etc. See the many posts below (Java especially, it seems),
- c# question has hints
- Rule of thumb answers in Scala, but seems to muddle linear synchronisation with outright disaster?
- Dark information on Java's thread visibility issue. One post suggests, yes, reference writing is atomic
- Java question related to this. More of the same Java confusion between visibility and objects being unformed
- immutable-objects-are-thread-safe-but-why Java question. Sounds like the right question, but what kind of thread safety?
- .net question slews off course
I'd like to work this question on a smaller scale...