What role does the Arrays.copyOf array play in making the class immutable?

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);     // 1
    }

    public BigInteger[] getFactors(BigInteger i){
        if(lastNumber == null || lastNumber.equals(i))
            return null;
        else
            return Arrays.copyOf(lastFactors,lastFactors.length);     // 2
    }
}

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); // cache being volatile, hence @ThreadSafe
        }

        encodeIntoResponse(resp, factors);
    }

}
+4
source share
1 answer

If you return this.lastFactorsinstead of returning a copy, the caller can do (for example)

BigInteger[] lastFactors = cache.getFactors(...);
for (int i = 0; i < lastFactors.length; i++) {
    lastFactors[i] = null;
}

and thus mutate the state of the cache, which should be unchanged.

The explanation is similar to a constructor. If the constructor did not make a copy, the caller could make

factors = factor(i);
cache = new OneValueCache(i, factors); 
for (int i = 0; i < lastFactors.length; i++) {
    factors[i] = null;
}

, , .

: ( ). , , .

+10

Source: https://habr.com/ru/post/1650448/


All Articles