In Brian Goetz Concurrency In practice, why does the last example of the scalable cache have some time (true)?

In Listing 5.19, Brian Goetz’s book Concurrency In practice, he introduces a ready-made Memoizer class.

I thought I understood the code in this example, except that I do not understand what

while ( true ) 

is at the beginning

 public V compute(final A arg) throws InterruptedException 

method.

Why does the code need a while loop?

Here is an example of the whole code

 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()); } } } } 
+6
java multithreading concurrency
source share
2 answers

The eternal loop repeats the CancellationException. If any other exception is thrown, execution will be stopped.

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

+8
source share

It seems that the main purpose of the code is to compute any type of A. It seems that the only way that while(true) can be effective is to undo. If there is a cancellation, then the method will repeat the calculation.

Basically, while(true) guarantees that (otherwise, an ExecutionException), at some point, the function will be completed and will be correctly calculated even with cancellation.

+1
source share

All Articles