В следующем коде (скопировано из Параллелизм в Java на практике Глава 2, раздел 2.5, листинг 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);
}
}
почему массивы factors
, lastFactors
клонированы? Разве это не может быть просто записано как factors = lastFactors;
и lastFactors = factors;
? Просто потому, что factors
является локальной переменной и затем передается в encodeIntoResponse
, что может ее изменить?
Надеюсь вопрос ясен. Спасибо.