4 ms·
> If you have a reference to a junk instance Step back a bit: where did the junk instance come from? The Java rules guarantee that a String created through the
by cesarb 9y ago
> If you have a reference to a junk instance
Step back a bit: where did the junk instance come from? The Java rules guarantee that a String created through the String constructors is valid on any thread that can see it. There are no "junk instances" of String. Also, writing to an object reference variable is indivisible: either a thread doesn't see the write, or it sees the full write.
So there are only two states in which a thread can see the stringCache field: either it is null, or it has a reference to a valid String. It might not see the field write from another thread, but in this case this only leads to duplicating work and leaving a bit of garbage on the heap for the GC to clean.
(Of course, once you start using reflection to manipulate internal fields of an object, then all bets are off, but that's not the case here.)