Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why isn't java.lang.Class.newInstance0() strictly correct under the java memory model?

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?

like image 419
SpaceTrucker Avatar asked Nov 01 '12 12:11

SpaceTrucker


2 Answers

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.

like image 117
Ievgen Lukash Avatar answered Nov 11 '22 22:11

Ievgen Lukash


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.

like image 29
irreputable Avatar answered Nov 11 '22 23:11

irreputable