Extract / slice from Java Concurrency in practice -
@Immutable
class OneValueCache{
private final BigInteger lastNumber;
private final BigInteger[] lastFactors;
public OneValueCache(BigInteger i, BigInteger[] factors) {
this.lastNumber = i;
this.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);
}
}
The author mentions
OneValueCache will not be immutable without calling copyOf to the constructor and getter. Arrays.copyOf was added as a convenience in Java 6; the clone will also work.
1) What role does Arrays.copyOf play in making the class above as IMMUTABLE? How?
The above immutable class is used like this:
@ThreadSafe
public class VolatileCachedFactorizer 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);
cache = new OneValueCache(i, factors);
}
encodeIntoResponse(resp, factors);
}
}
source
share