Java specification mentions that classes having only final fields have their constructors in a happens-before relation with any thread reading any reference to that object: in other words, it is not possible for the application to see a partially constructed object.
Scala hacks initialization by extracting it to separate methods in order to ensure that 'primary constructor vals' are set before any initializing code in superclasses. This is at least one reaason why Scala final val doesn't translate always (or ever?) to a Java final field.
- Is there a way to achieve this, i.e. ensure the happens-before relation between class clients and its constructors?
- One which is a reasonably stable feature of the compiler?
- One which is not writing the class in Java?
In java that doesn't break
finalguarantees as long asthisdoesn't escape from the constructor.("doesn't escape" means that constructor's code doesn't store
thisin a variable/collection/etc which can be read by another thread)Also because the JMM is defined for java language and not for the JVM, I'm afraid it only works in languages that compile to java code.