Build an efficient and scalable result cache
Extracted from
Public interface Computable {V comput (An arg);}
Import java.util.concurrent.*;/** * build an efficient scalable result cache *
* author: shiruiqiang * time: 31 arg 23:11 * * / public class Memoizer implements Computable {private final ConcurrentHashMap cache = new ConcurrentHashMap (); private Computable c; public Memoizer (Computable c) {this.c = c;} public V comput (An arg) {while (true) {Future f = cache.get (arg) If (f = = null) {/ / check whether it already exists in the cache, and if not, create Callable task = new Callable () {@ Override public V call () throws Exception {return c.comput (arg);}} FutureTask ft = new FutureTask (task); f = cache.putIfAbsent (arg, ft); / / Atomic operation, if (f = = null) {/ / if there is no such result in the cache, execute the task calculation result f = ft; ft.run () }} try {return f.get (); / / Block, waiting for the result. If it is already in the cache, it will not block} catch (CancellationException e) {cache.remove (arg, f);} catch (Exception e) {e.printStackTrace ();}
The above code has many benefits.
1: calculation is isolated from cache and decoupled
2: thread safety
3: support concurrency
4: do not repeat calculation when concurrent, efficient