Java中的并发缓存 [英] Concurrent Cache in Java

查看:188
本文介绍了Java中的并发缓存的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找对Brian Goetz的并发书中的以下代码的解释。

  public V compute(final A arg) throws InterruptedException {
while(true){
Future< V> f = cache.get(arg);
if(f == null){
Callable< V> eval = new Callable< V>(){
public V call()throws InterruptedException {
return c.compute(arg);
}
};
FutureTask< V> ft = new FutureTask< V>(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){
throw larowThrowable(e.getCause());
}
}
}

此外,putIfAbsent )调用为什么语句 f = ft; 而不是直接做一个ft.run()?

putIfAbsent 的返回值是现有的,如果已经存在或 null 如果没有一个,我们把新的一个。

  f = cache.putIfAbsent(arg,ft); 

if(f == null){
f = ft;
ft.run();
}

因此 if(f == null)表示我们在缓存中放置 ft 。显然,如果我们 把它放在缓存中,我们现在需要将 f 设置为缓存中的一个,即如果我们没有在缓存中放置 ft ,那么<$ c

$ c> f 已经是缓存中的一个,因为它是 putIfAbsent 返回的值。


Im looking for an explanation to the following code from Brian Goetz's concurrency book.

public V compute(final A arg) throws InterruptedException {
    while (true) {
        Future<V> f = cache.get(arg);
        if (f == null) {
            Callable<V> eval = new Callable<V>() {
                public V call() throws InterruptedException {
                    return c.compute(arg);
                }
            };
            FutureTask<V> ft = new FutureTask<V>(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) {
            throw launderThrowable(e.getCause());
        }
    }
}

Also, after the putIfAbsent() call why the statement f = ft; and not just directly do a ft.run() ?

解决方案

The return value of putIfAbsent is the existing one if one was already there or null if there wasn't one and we put the new one in.

        f = cache.putIfAbsent(arg, ft);

        if (f == null) {
            f = ft;
            ft.run();
        }

So if ( f == null ) means "Did we put ft in the cache?". Obviously, if we did put it in the cache we now need to set f to the one in the cache, i.e. ft.

If we did not put ft in the cache then f is already the one in the cache because it is the value returned by putIfAbsent.

这篇关于Java中的并发缓存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆