Why does java.lang.Class.newInstance0 () strictly correspond to the java memory model?

I met the following note in java.lang.Class.newInstance0() in JDK 1.7 Update 7:

NOTE. The following code may not be entirely correct in the current Java memory model.

Can someone explain why?

+8
java memory-model
source share
2 answers

The only problem in this code that I see is that the β€œcachedConstructor” field is mutable, while it guarantees the visibility effect among the threads, this particular code block has the fancy that different threads can see that cachedConstructor is equal null before the value will be assigned by one of the threads, i.e. the initialization sequence is not atomic. This can only lead to the fact that cachedConstructor can be assigned a couple of times at the same time, but will not violate the code if no one believes that it will be the same instance of Constructor. If the cachedConstructor initialization block is synchronized, it will be atomic, i.e. CachedConstructor is assigned only once, regardless of race condition.

However, the code should work as expected, but just allows you to simultaneously redistribute the cached value to more than one thread.

+5
source share

current java memory model

The question is, "how is the current."

This piece of code is probably very ancient, 1.4 or earlier, and since then no one has touched it.

The author probably knew that a new memory model was being developed.

+1
source share

All Articles