I came across the following note in java.lang.Class.newInstance0()
in JDK 1.7 Update 7:
NOTE: the following code may not be strictly correct under the current Java memory model.
Can anybody please explain why?
The only issue in this code that I can see is that "cachedConstructor" field is volatile, while it guarantees value visibility effect among threads, this particular code block have a quirk that different threads could see cachedConstructor as null before the value will be assigned by one of threads, i.e. initialisation sequence is not atomic. This can only lead that cachedConstructor may be assigned couple of times simultaneously, but will not break the code if nobody specifically relies that it will be the the same Constructor instance. If the cachedConstructor initialisation block would be synchronised, then it will be atomic, i.e. cachedConstructor assigned only once regardless of race condition.
That said, code should work properly, but just allows to concurrent excessive recomputation of cached value by more than one thread.
the current Java memory model
The question is "how current".
That piece of code is likely very ancient, 1.4 or earlier, and nobody touched it since.
The author was probably aware that a new memory model was being worked on.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With