I'm reading the book Java concurrency in practice and when I read about the relation between immutability and thread-safety I tried to get deeper. So, I discovered that there is at least a use case in which the construction of an immutable class in Java can lead to the publishing of a non properly constructed object.
According to this link, if the fields of the class are not declated final
, the compiler could reorder the statements that needs to be done in order to construct the object. In fact, according to this link, to build an object the JVM needs to do these non-atomic operations:
- allocate some memory
- create the new object
- initialise its fields with their default value (false for boolean, 0 for other primitives, null for objects)
- run the constructor, which includes running parent constructors too
- assign the reference to the newly constructed object
My question is: what about Scala? I know that Scala is based on the concurrency model of Java, so it is based on the same Java Memory Model. For example, are case class
es thread-safe wrt the above construction problem?
Thanks to all.