Concurrent Cache in Java

大城市里の小女人 提交于 2019-12-24 15:27:55

问题


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


回答1:


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.




回答2:


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.




回答3:


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..



来源:https://stackoverflow.com/questions/16484939/concurrent-cache-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!