Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Brian Goetz Concurrency In Practice, why is there a while(true) in the final example of a scalable cache?

In code listing 5.19 of the Brian Goetz book Concurrency In Practice, he presents his finished thread safe Memoizer class.

I thought I understood the code in this example, except that I don't understand what the

while ( true )

is for at the start of the

public V compute(final A arg) throws InterruptedException

method.

Why does the code need the while loop?

Here is the entire code sample

public class Memoizer<A, V> implements Computable<A, V> {
    private final ConcurrentMap<A, Future<V>> cache
        = new ConcurrentHashMap<A, Future<V>>();
    private final Computable<A, V> c;

    public Memoizer(Computable<A, V> c) { this.c = c; }

    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());
            }
        }
    }
}
like image 263
russelldb Avatar asked Oct 07 '10 13:10

russelldb


1 Answers

Eternal loop retries on CancellationException. If any other exception is being thrown the execution will be stopped.

Biotext dot org has a blog entry on the same issue.

like image 118
Boris Pavlović Avatar answered Sep 21 '22 12:09

Boris Pavlović