java并发编程实践代码错误,看java并发编程实践对ConcurrentHash使用方法的疑问

根据书里面的实现高效本次缓存的代码,下面的代码的前提是,假设有一个很耗时的计算,并且计算结果可以重用,我想将这个计算结果缓存在map里,并且保证计算过程(代码中的Callable代码)只会被执行一次。

private final ConcurrentHashMap> cache = new ConcurrentHashMap>();

private final Computable c;

public Memoizer(Computable c) {

this.c = c;

}

/* (non-Javadoc)

* @see com.demo.buildingblocks.Computable#compute(java.lang.Object)

*/

@Override

public V compute(final A arg) throws InterruptedException {

while (true) {

Future f = cache.get(arg);

if (f == null) {

//

Callable eval = new Callable() {

@Override

public V call() throws Exception {

return c.compute(arg);

}

};

FutureTask ft = new FutureTask(eval);

// **这里**

f = cache.putIfAbsent(arg, ft);

if (f == null) {

f = ft;

ft.run();

}

}

try {

return f.get();

} catch (CancellationException e) {

cache.remove(arg, f);

} catch (ExecutionException e) {

launderThrowable(e);

}

}

}

public static RuntimeException launderThrowable(Throwable t) {

if (t instanceof RuntimeException)

return (RuntimeException) t;

else if (t instanceof Error)

throw (Error) t;

else

throw new IllegalStateException("Not unchecked", t);

}

我的分析是,putIfAbsent既然只能保证原子性,如果两个线程同时执行这个方法,那么会同时返回null,继而同时进入下面的if代码块,最后还是会导致compute执行了两次。

如果分析错误,那么正确的理解应该是怎样的呢?

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值