Concurrent Cache in Java

2019-07-22 11:38发布

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() ?

3条回答
▲ chillily
2楼-- · 2019-07-22 11:49

The idea of the code is as follows. Request to compute some values originate from different threads. If one thread have initiated computing of some value, other threads which need the same result, should not duplicate computing, and should wait for the initial computing instead. When computing is finished, the result is kept in the cache.

Example of such a pattern is loading of java classes. If a class is being loaded, and another thread also requests loading of the same class, it should not load it itself, but wait for result of the first thread, so that there is always no more than on instance of the given class, loaded by the same classloader..

查看更多
Explosion°爆炸
3楼-- · 2019-07-22 12:09

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.

查看更多
Fickle 薄情
4楼-- · 2019-07-22 12:13

Because you're returning f.get() and possibly removing f from the cache. This allows one piece of code to work for all instances.

    try {
        return f.get();
    } catch (CancellationException e) {
        cache.remove(arg, f);

If you didn't replace f with the reference to ft in the above, you'd get an NPE EVERY time putIfAbsent returned null.

查看更多
登录 后发表回答