首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >最后一次计算的结果可以直接使用吗?Java同步块

最后一次计算的结果可以直接使用吗?Java同步块
EN

Stack Overflow用户
提问于 2022-01-11 11:32:17
回答 1查看 49关注 0票数 0

为什么当两个连续的请求分解相同的值时,同步块能够直接使用前面的计算结果?

Java并发性的2-8代码在实践中

代码语言:javascript
复制
    public class two_8_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;
    }
    @Override
    public  void service(ServletRequest req, ServletResponse res) throws ServletException, IOException {
        BigInteger i=extractFromRequest(req);
        BigInteger[] factors=null;
        synchronized (this) {
            ++hits;
            if (i.equals(lastNumber)) {
                ++cacheHits;
                factors = lastFactors.clone();
            }
        }
            if (factors==null)
            {
                factors=factor(i);//question in here :Suppose two identical requests arrive here at the same time
                synchronized (this)
                {
                    lastNumber=i;
                    lastFactors=factors.clone();
                }
            }
            encodeIntoResponse(res,factors);
        }

}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-01-11 11:56:23

我相信你手上至少有种族的条件。可能是较早发布的factor(i)在较晚发布的factor(i)之后完成;重写后发布的factor(i)的值。因此,lastFactor和lastNumber可以更新为更早的版本。为了解决这个问题,我将在最后一个同步块中添加一些检查。

在当前代码中,可以让多个线程执行相同的计算。我不确定这是否可取。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/70666072

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档