【发布时间】:2022-01-11 11:32:17
【问题描述】:
为什么Synchronized block在连续两次请求分解同一个值时可以直接使用之前的计算结果?
Java Concurrency in Practice 2-8 的代码
public class two_8_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;
}
@Override
public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException {
BigInteger i=extractFromRequest(req);
BigInteger[] factors=null;
synchronized (this) {
++hits;
if (i.equals(lastNumber)) {
++cacheHits;
factors = lastFactors.clone();
}
}
if (factors==null)
{
factors=factor(i);//question in here :Suppose two identical requests arrive here at the same time
synchronized (this)
{
lastNumber=i;
lastFactors=factors.clone();
}
}
encodeIntoResponse(res,factors);
}
}
【问题讨论】:
-
您的问题到底是什么?如果您希望一个线程等待另一个线程,因为它们都计算相同的值,那么在您提到的书中; Future 会有这样的实现。
-
lastFactors、cacheHits等在哪里定义?请发帖minimal reproducible example。
标签: java multithreading java.util.concurrent