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

StackOverflow https://stackoverflow.com/questions/13177298

  •  25-07-2021
  •  | 
  •  

سؤال

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.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top