I had an example from the book "java concurrency pratique" that says an unstable and immutable holder object provides thread safety. But I do not understand the example given in the book.
The code is as follows:
public class VolatileCachedFactorizer extends GenericServlet implements Servlet { private volatile OneValueCache cache = new OneValueCache(null, null); public void service(ServletRequest req, ServletResponse resp) { BigInteger i = extractFromRequest(req); BigInteger[] factors = cache.getFactors(i); if (factors == null) { factors = factor(i);
I understand that
But I can not understand why the VolatileCachedFactorizer class is thread safe.
For two threads (Thread A and Thread B), if thread A and thread B come to factors == null at the same time, two threads A and B will try to create OneValueCache. Then Thread A comes to factors = factor(i) , and threadB comes to cache = new OneValueCache(i, factors) at the same time. Then thread A will create OneValueCache , which overwrites the value created by threadB (OneValueChange is unchanged, but the reference to the variable cache can be changed).
This indicates that the code is not thread safe.
Can someone tell me why this piece of code is considered thread safe and why am I mistaken?
source share