0

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?

tmsimont
  • 2,651
  • 2
  • 25
  • 36
  • 2
    "is it possible that some kind of half-written garbage data is returned" No. The reference is written atomically. – Andy Turner Oct 05 '17 at 20:45
  • Take a look on double-checking idiom. – Sergey Morozov Oct 05 '17 at 20:56
  • I'm not sure if you're asking whether the reference itself will be malformed, or whether you mean it will correctly reference a partially-constructed String. But both are impossible. In the latter case, it's impossible because Strings only use `final` fields, which have special semantics in multithreading (well, a String's hashCode is cached in a non-final, unsafe way... but that works due to more subtle reasons, so for these purposes you can ignore it). – yshavit Oct 05 '17 at 21:03

0 Answers0