Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala and the Java Memory Model

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)

like image 789
Ben Lings Avatar asked Mar 17 '10 12:03

Ben Lings


People also ask

Can you explain the Java memory model?

The Java Memory Model (JMM) defines the allowable behavior of multithreaded programs, and therefore describes when such reorderings are possible. It places execution-time constraints on the relationship between threads and main memory in order to achieve consistent and reliable Java applications.

What are the memory management of Java?

Memory management is the process of allocating new objects and removing unused objects to make space for those new object allocations. This section presents some basic memory management concepts and explains the basics about object allocation and garbage collection in the Oracle JRockit JVM.

What is JVM memory pool?

A memory pool represents the memory resource managed by the Java virtual machine and is managed by one or more memory managers . A Java virtual machine has one or more instances of the implementation class of this interface.

What is JVM and explain me the Java memory allocation?

Java Memory Structure: JVM defines various run time data area which are used during execution of a program. Some of the areas are created by the JVM whereas some are created by the threads that are used in a program. However, the memory area created by JVM is destroyed only when the JVM exits.


2 Answers

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

  • Bug Report October 2007
  • Commit November 2007

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

like image 171
retronym Avatar answered Oct 17 '22 22:10

retronym


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)

like image 22
oxbow_lakes Avatar answered Oct 17 '22 20:10

oxbow_lakes