Handy Utility class for guarding computation of function with a check-function This is a Function and you can give a function 'witness' that's . If the witness function returns something that's different from the last time it returned (or this cache has been
| 13 | * return value stored and return. Otherwise, you get the same result as before. |
| 14 | */ |
| 15 | public class Cached<t_check, t_witness, t_value> implements Function<t_check, t_value> { |
| 16 | |
| 17 | private BiFunction<t_check, t_value, t_value> compute; |
| 18 | private final Function<t_check, t_witness> witness; |
| 19 | private t_witness valid; |
| 20 | private t_value value; |
| 21 | private boolean invalid = false; |
| 22 | private String debug = null; |
| 23 | |
| 24 | public Cached(BiFunction<t_check, t_value, t_value> compute, Function<t_check, t_witness> witness) { |
| 25 | this.witness = witness; |
| 26 | this.compute = compute; |
| 27 | invalid = true; |
| 28 | } |
| 29 | |
| 30 | public Cached<t_check, t_witness, t_value> setCompute(BiFunction<t_check, t_value, t_value> compute) { |
| 31 | this.compute = compute; |
| 32 | return this; |
| 33 | } |
| 34 | |
| 35 | public Cached<t_check, t_witness, t_value> invalidate() { |
| 36 | if (debug != null) Log.log("cached." + debug, ()->" cache invalidated :"); |
| 37 | invalid = true; |
| 38 | return this; |
| 39 | } |
| 40 | |
| 41 | public t_value apply(t_check check) { |
| 42 | t_witness w; |
| 43 | try { |
| 44 | w = witness.apply(check); |
| 45 | } |
| 46 | catch(Throwable t) |
| 47 | { |
| 48 | System.err.println(" exception thrown by witness :"+witness+" carying on"); |
| 49 | t.printStackTrace(); |
| 50 | w=null; |
| 51 | invalid = true; |
| 52 | } |
| 53 | |
| 54 | t_witness finalW = w; |
| 55 | if (invalid || !Util.safeEq(w, valid)) { |
| 56 | if (debug != null) { |
| 57 | Log.log("cached." + debug, ()->" cache invalid :" + invalid + " " + finalW + " " + valid + " " + Util.safeEq(finalW, valid)); |
| 58 | } |
| 59 | value = compute.apply(check, value); |
| 60 | valid = w; |
| 61 | |
| 62 | if (valid instanceof Mutable) |
| 63 | valid = (t_witness) ((Mutable)valid).duplicate(); |
| 64 | |
| 65 | invalid = false; |
| 66 | } else if (debug != null) |
| 67 | Log.log("cached." + debug,()-> " cache valid :" + invalid + " " + finalW + " " + valid + " " + Util.safeEq(finalW, valid)); |
| 68 | return value; |
| 69 | } |
| 70 | |
| 71 | public Cached<t_check, t_witness, t_value> debugOn(String name) { |
| 72 | this.debug = name; |
no outgoing calls
no test coverage detected