volatile + immutable holder object = thread safe?

So, two threads compute factors (one for 67, and the other for 89), and then store their result into the cache variable. The last thread that sets the variable wins. Let's say the first thread is the last one to store its factors in the cache. The cache thus contains the factors for 67.

If a subsequent execution asks for the factors of 67, it will get them from the cache (because the cache is not null, and contains the factors for 67). If it asks for the factors of another number, it won't get them from the cache, will thus compute the factors, and store them in the cache, hoping that the following requests will ask for the factors of the same number.

Nothing guarantees that two threads won't compute the factors from the same number. The only guarantee that this code offers is that, if the cache currently contains the factors for the requested number, these cached factors will be returned (and not factors for another number, or inconsistent data cause by a data race)


There are two attributes to a thread-safe operation

  1. Visibility
  2. Atomicity

To have a completely thread-safe operation it needs to satisfy both requirements.

In your example it is safe of any data races (ie Visibility) (1) but is not atomic (2). Chances are, the author wanted to illustrate that the code above is safe for publication and neglected to point out (or maybe you hadn't read) that it was not atomic.

Could anyone tell me why this piece of code is considered as thread safe and why i am wrong ?

Your inclination here is right and your questioning the safety of this class is legitimate.