Roh*_*ana 5 java concurrency multithreading
下面是Java Concurrency in Practice(清单 2.8)中的一个线程安全类示例。
我的问题是下面的类如何是线程安全的?
例如,如果两个线程Thread A,并Thread B进入CachedFactorizer的服务方法。Thread B其次是Thread A。现在 ifThread A正在执行第一个同步块并且Thread B显然在等待对象的内在锁。如果Thread B在到达第二个同步块之前Thread A到达第一个同步块,它将查看一个陈旧的值,并且这种情况可能被称为Race Condition。
那么,我的理解对吗?还是我对并发缺乏一些基本的了解?
@ThreadSafe
public class 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;
}
public void service(ServletRequest req, ServletResponse resp) {
BigInteger i = extractFromRequest(req);
BigInteger[] factors = null;
synchronized (this) {
++hits;
if (i.equals(lastNumber)) {
++cacheHits;
factors = lastFactors.clone();
}
}
if (factors == null) {
factors = factor(i);
synchronized (this) {
lastNumber = i;
lastFactors = factors.clone();
}
}
encodeIntoResponse(resp, factors);
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
314 次 |
| 最近记录: |