Memory visibility for constructed objects


#1

I tried to find anything more specific about the memory model and Kotlin. So far unsuccessfully ?:| Is there any specification of this topic already?

Well, I assume that the memory model in Kotlin won’t be much surprising: I saw there is synchronized and volatile, I guess that using atomic variables and any concurrent classes from Java won’t be problem either. However, Kotlin has a few features where I can merely guess, not knowing all the internals, whether they offer any memory visibility guarantees.

For instance, Java guarantees correct memory visibility for final fields of properly constructed objects. Pretty clear: field is a field, it is an explicitly declared memory location, final makes constructors set it. Kotlin properties, with their automatic backing fields (possibly accessible explicitly with the $ prefix), are not clear from this point of view to me at all. And when starting thinking about delegating, lazy properties etc., it becomes completely unclear. I could not find, for instance, even whether the delegation link is final (from the JVM’s point of view at least).

I’m at the very beginning of learning Kotlin, but I already find it very promising :x Even so much, that I decided to try to move from Eclipse to IntelliJ. So I hope that neither Kotlin, nor IntelliJ let me down. Details are important!


#2

Unfortunately, there's not enough documentation so far, and your best resort is peeking at the bytecode for details (use the Kotlin Bytecode view in the IDE).

Answering your questions:

  • If you are running on the JVM, then you are using the Java memory model, semantics of volatile, synchronozed, atomics etc are the same as in Java.

  • Backing fields of val’s have the final flag.
  • Delegation links have the final flag.
  • Lazy properties are not a language feature, please refer to implementation/docs of the specific delegate classes.


Hope it helps


#3

Peeking in the bytecode can always help, but the bytecode is nothing that can't change easily. I rather rely on specifications and documentation ;) So, thank you for reassuring me that it is intended to work in this way.