4 ms·
This is only true if you have a safe reference to that String. No safe reference has been established between stringCache and the String instance it points to.
by LgWoodenBadger 9y ago
This is only true if you have a safe reference to that String. No safe reference has been established between stringCache and the String instance it points to.
Assuming you have a safe reference (through a safe publication), then what you quoted comes into play. You do not need any synchronization mechanisms around a String in order to see its correct data, because the String instance is immutable.
Or to put it another way, why do you think other threads would see the value of stringCache change from
stringCache = "this is my value in thread 1.";
to
stringCache = "this is a different value set by another thread without a safe publication of the stringCache reference.";
without establishing a happens-before relationship through a memory barrier?
You wouldn't. That's why there are AtomicLong, AtomicBoolean, and AtomicInteger. Long, Boolean, and Integer are all immutable, but you can't use them without establishing happens-before. AtomicReference could have been used to get the correct behavior intended by stringCache, but AtomicReference didn't exist until 1.5.
- cesarb 9y ago> Or to put it another way, why do you think other threads would see the value of stringCache change True, other threads might not see the value of stringCache change. However, if and when they see it change, they will see it change to another valid String. They will never see an incompletely initialized String. Using AtomicReference or volatile gives you stronger guarantees, but they're not necessary here.