Java – is delayed initialization using immutable data always thread safe?
I have two classes a and B:
class A { private final String someData; private B b; public String getSomeData() { return someData; } public B getB() { if (b == null) { b = new B(someData); } return b; } }
Where B is immutable and its data is calculated only from the instance of A A has immutable semantics, but its internal is variable (such as hashcode in Java. Lang. string)
When I call getb () from two different threads and the calls overlap, I assume that each thread has its own B instance However, since B's constructor only gets immutable data, the two instances of B should be equal
Is that right? If not, do I have to synchronize getb () to make it thread safe?
Suppose B implements equals (), which compares all instance variables of B For hashcode ()
Solution
This is not thread safe, because you have not created any "pre - occurrence" relationship related to volatile, so the two threads may interfere with each other
The problem is that although B = New B (somedata) means "allocate enough memory for the instance of B, then create the instance there, and then point B to it", the system can implement it as an instance of "allocate enough memory for it" B, and then point B to it, Then create an instance "(because, in a single threaded application, this is equivalent). Therefore, in your code, two threads can create a separate instance but return the same instance. One thread may return the instance of another thread before the instance is fully initialized