'Happens before' on Scala constructors: final fields

146 Views Asked by At

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.

  1. Is there a way to achieve this, i.e. ensure the happens-before relation between class clients and its constructors?
  2. One which is a reasonably stable feature of the compiler?
  3. One which is not writing the class in Java?
1

There are 1 best solutions below

0
user16783328 On

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.

In java that doesn't break final guarantees as long as this doesn't escape from the constructor.
("doesn't escape" means that constructor's code doesn't store this in 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.