14

The Java Memory Model (since 1.5) treats final fields differently to non-final fields. In particular, provided the this reference doesn't escape during construction, writes to final fields in the constructor are guaranteed to be visible on other threads even if the object is made available to the other thread via a data race. (Writes to non-final fields aren't guaranteed to be visible, so if you improperly publish them, another thread could see them in a partially constructed state.)

Is there any documentation on how/if the Scala compiler creates final (rather than non-final) backing fields for classes? I've looked through the language specification and searched the web but can't find any definitive answers. (In comparison the @scala.volatile annotation is documented to mark a field as volatile)

3 Answers 3

5

I dug through the history to find out when the change was made.

The projection of Scala into the JVM isn't covered by the language specification.

Sign up to request clarification or add additional context in comments.

1 Comment

But the behaviour, from a concurrency perspective, of language constructs should be part of its specification I would argue!
3

It creates a final field when you declare something as a val. Anything whose references can be modified, such as a var, can (obviously) not be final underneath.

This means that case classes contain final fields also (as the arguments to a case class constructor are implicitly vals)

2 Comments

I don't think this used to be the case (see old.nabble.com/Val-and-Final-td13355515.html for example). Part of the reason for my question - if this can change without any documentation, how do I know it won't change again?
You are correct that this should have been documented. This is not merely an issue of performance but part of the language itself due to the memory model. I was not aware that vals used to be non-final
2

I've filed a documentation bug for this in the Scala bug system.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.