Java – volatile variables that will never be assigned null will never contain null?
•
Java
You can use the following concepts in java examples:
public class X implements Runnable { public volatile Object x = new Object(); @Runnable public void run() { for (;;) { Thread.sleep(1000); x = new Object(); } } }
X read null from another thread?
Bonus: I need to declare that it is fluctuating (I really don't care about this value, as long as it will be a newly allocated value at some time in the future, never null)
Solution
Technically, yes, it is This is the main reason for the original concurrent HashMap's readunderlock Javadoc even explains how to:
Because the value of hashentry is unstable, this type of reordering is legal
The moral of the story is that all non - Final initializations can compete with object constructs
Editor: @ Nathan Hughes asked a valid question:
Doug lea has several comments on this topic. The whole topic can be read here He answered this comment:
There's an answer
And completed:
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码