这是我的代码..如何以及为什么此代码是线程安全的..?
@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