29

In Java, when using an object across multiple threads (and in general), it is good practice to make fields final. For example,

public class ShareMe {
    private final MyObject obj;
    public ShareMe(MyObject obj) {
        this.obj = obj;
    }
}

In this case, the visibility of obj will be consistent across multiple threads (let's assume obj has all final fields as well) since it is safely constructed using the final keyword.

In scala, it doesn't appear val compiles down to a final reference, but rather val is semantics in scala that prevents you from reassigning a variable (Scala final variables in constructor). If scala constructor variables are not defined as final, will they suffer from the same problem (when using these objects in actors)?

Community
  • 1
  • 1
Jeff Storey
  • 56,312
  • 72
  • 233
  • 406

2 Answers2

54

The answer to the other question is misleading. There are two meanings of the term final: a) for Scala fields/methods and Java methods it means "cannot be overridden in a subclass" and b) for Java fields and in JVM bytecode it means "the field must be initialized in the constructor and cannot be reassigned".

Class parameters marked with val (or, equivalently, case class parameters without a modifier) are indeed final in second sense, and hence thread safe.

Here's proof:

scala>  class A(val a: Any); class B(final val b: Any); class C(var c: Any)
defined class A
defined class B
defined class C

scala> import java.lang.reflect._
import java.lang.reflect._

scala> def isFinal(cls: Class[_], fieldName: String) = {
     |   val f = cls.getDeclaredFields.find(_.getName == fieldName).get
     |   val mods = f.getModifiers
     |   Modifier.isFinal(mods)
     | }
isFinal: (cls: Class[_], fieldName: String)Boolean

scala> isFinal(classOf[A], "a")
res32: Boolean = true

scala> isFinal(classOf[B], "b")
res33: Boolean = true

scala> isFinal(classOf[C], "c")
res34: Boolean = false

Or with javap, which can be conveniently run from the REPL:

scala> class A(val a: Any)
defined class A

scala> :javap -private A
Compiled from "<console>"
public class A extends java.lang.Object implements scala.ScalaObject{
    private final java.lang.Object a;
    public java.lang.Object a();
    public A(java.lang.Object);
}
retronym
  • 54,768
  • 12
  • 155
  • 168
  • thanks for that clarification. Can you see my update to that question? I'm also seeing the constructor variables declared as final (as shown in javap) for a non case class with no modifier. – Jeff Storey Oct 02 '11 at 14:31
  • @retronym, I came to your answer trying to find an answer to my question, [Immutability and thread-safety in Scala](http://stackoverflow.com/questions/32113124/immutability-and-thread-safety-in-scala). As you know, the `final` keyword in Java is used also to avoid the relocation of the instructions of the ctor, as stated in [this](https://www.cs.umd.edu/~pugh/java/memoryModel/jsr-133-faq.html#finalRight) link. So, if I have understood right your answer, using a `val` field in a Scala class equals to declaring a `final` field in a Java class, letting the JMM working properly? – riccardo.cardin Aug 21 '15 at 18:58
1

I think I may have misunderstood how var is compiled. I created the sample class

class AVarTest(name:String) {
   def printName() {
     println(name)
   }
}

I ran javap -private and it resulted in

public class AVarTest extends java.lang.Object implements scala.ScalaObject{
    private final java.lang.String name;
    public void printName();
    public AVarTest(java.lang.String);
}

And name is actually compiled to final.

This is also shown in Scala val has to be guarded with synchronized for concurrent access?

Community
  • 1
  • 1
Jeff Storey
  • 56,312
  • 72
  • 233
  • 406
  • 2
    Note that as of 2.9.0.1 (maybe earlier) the only reason that you end up with a field name is because you referenced it in printName. If no methods reference a ctor argument it no long generates a field. – Duncan McGregor Oct 02 '11 at 19:18