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?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
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.