为何在实践中并发提到VolatileCachedFactorizer是线程安全的?

时间:2019-02-09 10:53:37

标签: java concurrency

我无法理解为什么在实践中并发提到的以下程序是线程安全的。它们来自第3.12和3.13章

class OneValueCache {
private final BigInteger lastNumber;
private final BigInteger[] lastFactors;

public OneValueCache(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);
    }
}   
}
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);
}
}

如果多个线程尝试使用服务方法会怎样? 我们如何将程序视为线程安全的?我想知道一些解释。

0 个答案:

没有答案