【发布时间】:2018-05-22 09:06:27
【问题描述】:
下面是Java Concurrency in Practice(Listing 2.8)一书中的一个线程安全类的示例。
我的问题是下面的类是如何线程安全的?
例如如果两个线程Thread A和Thread B进入CachedFactorizer的服务方法。 Thread B 后跟 Thread A。现在如果Thread 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);
}
}
【问题讨论】:
-
你能具体说明你关心的陈旧变量吗?
-
所有状态变量。hits、factors、lastfactors 和 cachehits。
-
你不是第一个质疑这个例子的,虽然这个例子是关于使用
clone():stackoverflow.com/questions/12034370/…
标签: java multithreading concurrency