為什么 Synchronized 塊在連續兩次請求分解同一個值時可以直接使用之前的計算結果?
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);
}
}
uj5u.com熱心網友回復:
我相信你手頭至少有一個比賽條件。可能是較早的發行factor(i)在較晚的發行之后完成factor(i);覆寫后面發出的值factor(i)。所以 lastFactor 和 lastNumber 可以更新到較早的版本。為了解決這個問題,我會在最后一個同步塊中添加一些檢查。
在當前代碼中,您可以讓多個執行緒執行相同的計算。我不確定這是否可取。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/408206.html
標籤:
上一篇:如果表為空,則顯示訊息
