這是我的代碼..如何以及爲什麼此代碼是線程安全的..?
@immutable // This is not a standard annotation .Only for Showing that behavior of Class
class OneValueCached{
private final BigInteger lastNumber;
private final BigInteger[] lastFactors;
public OneValueCached(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);
}
}
@threadSafe // This is not a standard annotation .Only for Showing that behavior of Class
public class VolatileCachedFactorizer implements Servlet{
private volatile OneValueCached cache=new OneValueCached(null, null);
public void service(ServletRequest req, ServletResponce resp){
BigInteger i= extractFromRequest(req);
BigInteger[] factors=cache.getFactors(i);
if(factors==null){ // ---> line 1
factors=factor(i); // --> line 2
cache=new OneValueCached(i, factors);
}
encodeIntoResponse(resp,factors);
}
}
爲什麼類VolatileCachedFactorizer是線程根據書但我的觀點是...
1 @ 1號線如果2線程在同一時間到來在這一點上第一個thread
檢查條件,發現因子= null和第二個thread
也檢查同一條件後第1 thread
暫停在線第2發現係數= NULL
,都將是創造新的OneValueCached
對象的代碼再怎麼是線程安全的。根據預訂是線程安全的..
感謝的
「@ threadSafe」是什麼註釋?它可能是打字錯誤,也可能不是標準註釋,因爲標準命名約定是'@ ThreadSafe'。 (相同的@ @不可變) – Thomas 2012-03-27 06:57:22
只是爲了通知,我知道這不是一個標準註釋... – 2012-03-27 06:58:37
'return lastFactors = Arrays.copyOf(lastFactors,lastFactors.length);'看起來很奇怪。它大概是內部數組的防禦副本,但是也會將內部狀態重新分配給它發出的同一個副本。這不再是防禦或不可改變的。其實,這是一個編譯錯誤,因爲'lastFactors'是最終的,不是? – Thilo 2012-03-27 07:11:01