"Java concurrency in practice" - a cached stream factor of numbers (Listing 2.8)

In the following code (copied from Java Concurrency in practice, Chapter 2, section 2.5, Listing 2.8):

@ThreadSafe
public class CachedFactorizer implements Servlet {
    @GuardedBy("this") private BigInteger lastNumber;
    @GuardedBy("this") private BigInteger[] lastFactors;
    @GuardedBy("this") private long hits;
    @GuardedBy("this") private long cacheHits;

    public synchronized long getHits() { return hits; }

    public synchronized double getCacheHitRatio() {
        return (double) cacheHits / (double) hits;
    }

    public void service(ServletRequest req, ServletResponse resp) {
        BigInteger i = extractFromRequest(req);
        BigInteger[] factors = null;
        synchronized (this) {
            ++hits;
            if (i.equals(lastNumber)) {
                ++cacheHits;
                factors = lastFactors.clone(); // questionable line here
            }
        }
        if (factors == null) {
            factors = factor(i);
            synchronized (this) {
                lastNumber = i;
                lastFactors = factors.clone(); // and here
            }
        }
        encodeIntoResponse(resp, factors);
    }
}

Therefore factors, do lastFactorsarrays clone? Can't it just be written like factors = lastFactors;that lastFactors = factors;? Just because they factorsare a local variable and then passed to encodeIntoResponse, which can change it?

I hope the question is clear. Thank you

+6
source share
5 answers

This is called security copying. Arrays are objects like any other, therefore

 factors = lastFactors

lastFactos . , . :

private void filterAndRemove(BigInteger[] arr);
private void encodeIntoResponse(..., BigInteger[] factors) {
   filterAndRemove(factors);
}

filterAndRemove lastFactorials.

+1

: , , , factors = lastFactors.clone(); , , lastFactors encodeIntoResponse(resp, factors);, .

0

( ) . , , lastFactors, . , factors lastFactors, factor, , .

encodeIntoResponse factors, , clone .

0

, .

, , ; , , encodeIntoResponse(...) : encodeIntoResponse(...) , factors .

: , factors - , , , , ( ) lastFactors encodeIntoResponse(...).

, @khachik @david-harkness , clone , lastFactors .

0

factors = lastFactors.clone(); factors = lastFactors; factors lastFactors , factors , .

, , A, B, C. , A B, 10, , C, 20. , , factors = lastFactors.clone(); factors = lastFactors; ,

  1. A, service , lastNumber 10, lastFactors [1, 2, 5, 10].
  2. - B, C, B, synchronized ( B factors [1, 2, 5, 10], ), C ,
  3. C service, lastFactors [1, 2, 5, 10] [1, 2, 4, 5, 10, 20], factors lastFactors , factors [1, 2, 4, 5, 10, 20] . , B [1, 2, 5, 10], [1, 2, 4, 5, 10, 20].
0

All Articles