Assume code like this:
public class UsedByManyThreads {
private String someString = null;
// ...
public String unsafeGetter() {
if (someString == null) {
someString = expensiveCalculationResult();
}
return someString;
}
// ...
}
If an instance of UsedByManyThreads is shared across many threads, and unsafeGetter()
is called simultaneously, is it possible that some kind of half-written garbage data is returned?
For example...
Let's say someString is null and thread A starts to calculate the expensiveCalculationResult()
.
Is is possible that someString
becomes non-null, such that some Thread B comes along and returns a value that is not fully written?
I understand that multiple threads might end up calculating expensiveCalculationResult()
in parallel, and then overwriting the someString
member repeatedly.
But let's say that expensiveCalculationResult()
always returns the same thing. Is there any danger in using code like this? Could someString
somehow be malformed?