为什么当两个连续的请求分解相同的值时,同步块能够直接使用前面的计算结果?
Java并发性的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);
}
}发布于 2022-01-11 11:56:23
我相信你手上至少有种族的条件。可能是较早发布的factor(i)在较晚发布的factor(i)之后完成;重写后发布的factor(i)的值。因此,lastFactor和lastNumber可以更新为更早的版本。为了解决这个问题,我将在最后一个同步块中添加一些检查。
在当前代码中,可以让多个线程执行相同的计算。我不确定这是否可取。
https://stackoverflow.com/questions/70666072
复制相似问题