Question

JMM (Java Memory Model) is free to reorder statements.

Of course, this is especially tricky when dealing with multithreading environment.

JMM rules precised that volatile and final variables are always fully initialized before constructor finishes and if and only if reference hasn't "escape" from within constructor.

It implies that "normal" variables (non-final and non-volatile) aren't expected to be seen up-to-date by any concurrent threads.

My question might seem stupid at first glance, but it really doesn't:

Are any object's references set AFTER constructor completes (completes not meaning with initialization of all variables already made, but simply reaching the end of the 'constructor' process)? Is there a rule in any JSR asserting it? Or might it exist an exceptional case where any reference could be sent back to client BEFORE constructor completes?

Indeed, if statements reordering is reputed so free, it may also imply the sending of the object's reference 'happens-before' constructor completes. So, we'd come across the same case of the "this escape" to avoid.

To put it in a nutshell, is reference ALWAYS be sent after constructor completes?

After searching into the JLS: the only place where returning of object's reference is related is: (excerpt of JSR-12.5)

Just before a reference to the newly created object is returned as the result, the indicated constructor is processed to initialize the new object using the following procedure:

No relation to JMM ... therefore it can be ensured that constructor completion always happens-before passing reference whatever the case.

Was it helpful?

Solution

Within the context of a thread the reference will be set. However, the JMM allows shared variables to be set in one thread and not yet synchronised to the other thread.

Volatile and final guarantee this by guaranteeing inter-thread synchronisation of reads and writes to the variable.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top