Immutability and thread-safety in Scala

时光总嘲笑我的痴心妄想 提交于 2019-12-05 14:13:08
riccardo.cardin

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 a case class and compiled by scalac. I found that the class

case class A(val a: Any)

is compiled by the scala compiler into a corresponding Java class that declares its unique attribute a as final.

Compiled from "A.scala"
public class A implements scala.Product,scala.Serializable {
  // Final attribute
  private final java.lang.Object a;
  public static <A extends java/lang/Object> scala.Function1<java.lang.Object, A
> andThen(scala.Function1<A, A>);
  public static <A extends java/lang/Object> scala.Function1<A, A> compose(scala
.Function1<A, java.lang.Object>);
  public java.lang.Object a();
  public A copy(java.lang.Object);
  public java.lang.Object copy$default$1();
  public java.lang.String productPrefix();
  public int productArity();
  public java.lang.Object productElement(int);
  public scala.collection.Iterator<java.lang.Object> productIterator();
  public boolean canEqual(java.lang.Object);
  public int hashCode();
  public java.lang.String toString();
  public boolean equals(java.lang.Object);
  public A(java.lang.Object);
}

As we know, a case class in Scala generates automatically a bunch of utilities for us. But also a simple class like this

class A1(val a: Any)

is 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 has final attributes only. Due to the JMM of the JVM, this Scala class should be thread-safe during the construction process.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!