This is not thread-safe, because you haven't created any "happens-before" relationships with volatile
or synchronized
, so it's possible for the two threads to interfere with each other.
The problem is that although b = new B(someData)
means "allocate enough memory for an instance of B
, then create the instance there, then point b
to it", the system is allowed to implement it as "allocate enough memory for an instance of B
, then point b
to it, then create the instance" (since, in a single-threaded app, that's equivalent). So in your code, where two threads can create separate instances but return the same instance, there's a chance that one thread will return the other thread's instance before the instance is fully initialized.