It goes on thin ice, but here is the explanation. The visibility problem means that some threads can see the old version, and some - the new one. In our case, some threads see 0 , while others see cachedHashCode .
Themes that call hashCode() and see cachedHashCode will simply return it (the condition if (h == 0) not satisfied), and everything works.
But the threads that see 0 (even though cachedHashCode may have already been computed) will simply reprogram it again.
In other words, in the worst case, each thread will go into the branch, seeing 0 for the first time (for example, if it was ThreadLocal ).
Since computeHashCode() is idempotent (very important), both calling it several times (in different threads) and reassigning it again to the same variable should not have any side effects.
source share