This is the my code..
@immutable // This is not a standard annotation .Only for Showing that behavior of Class
class OneValueCached{
private final BigInteger lastNumber;
private final BigInteger[] lastFactors;
public OneValueCached(BigInteger i,BigInteger[] factors){
lastNumber=i;
lastFactors=Arrays.copyOf(factors, factors.length);
}
public BigInteger[] getFactors(BigInteger i){
if(lastNumber==null || !lastNumber.equals(i))
return null;
else
return Arrays.copyOf(lastFactors, lastFactors.length);
}
}
@threadSafe // This is not a standard annotation .Only for Showing that behavior of Class
public class VolatileCachedFactorizer implements Servlet{
private volatile OneValueCached cache=new OneValueCached(null, null);
public void service(ServletRequest req, ServletResponce resp){
BigInteger i= extractFromRequest(req);
BigInteger[] factors=cache.getFactors(i);
if(factors==null){ // ---> line 1
factors=factor(i); // --> line 2
cache=new OneValueCached(i, factors);
}
encodeIntoResponse(resp,factors);
}
}
Why class VolatileCachedFactorizer is thread according to Book But My point is..
1. @ Line 1 if 2 thread coming at same time at that point 1st thread check condition and found factor=null and 2nd thread also check same condition at the same time after 1st thread suspend at line 2nd and found factor=null
And both will be create new OneValueCached Object Then how this code is thread safe.. According to book this is thread safe..
Thank’s
It’s thread safe because there is never inconsistency between
lastNumberandlastFactorswhich could result in incorrect factoring. It makes no guarantees that the minimum amount of factoring will take place: theOneValueCachedcan be created more than once, but that’s still thread-safe.