Sum*_*ngh 5 java multithreading thread-safety
这是我的代码..
@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);
}
}
Run Code Online (Sandbox Code Playgroud)
为什么类VolatileCachedFactorizer是根据Book 的线程,但我的观点是..
1. @ 第 1 行 如果 2 个线程在该点同时到来第 1 个thread检查条件并发现factor=null并且第 2 个thread也在第 1 次thread 挂起后同时检查相同的条件在第2行,发现 factor=null
并且两者都将创建新OneValueCached对象然后这段代码是线程安全的..根据本书这是线程安全的..
谢谢
它是线程安全的,因为lastNumber和之间永远不会存在不一致lastFactors,这可能会导致不正确的因式分解。它不保证会发生最小数量的因式分解:OneValueCached可以多次创建,但这仍然是线程安全的。