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.
I've made some deep search on Stackoverflow and on the Internet. There is not so much information about the question I've made. I found this question on SO that has an interesting answer: Scala final vs val for concurrency visibility.
As proposed by @retronym I've used
javap -p A.class
to destructure a.class
file containing acase class
and compiled byscalac
. I found that the classis compiled by the scala compiler into a corresponding Java class that declares its unique attribute
a
asfinal
.As we know, a
case class
in Scala generates automatically a bunch of utilities for us. But also a simple class like thisis translated into a Java class that has a
final
attribute.Summarizing, I think we can say that a Scala class that has only
val
attributes is translated into a corresponding Java class that hasfinal
attributes only. Due to the JMM of the JVM, this Scala class should be thread-safe during the construction process.