View Javadoc
1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one or more
3    * contributor license agreements.  See the NOTICE file distributed with
4    * this work for additional information regarding copyright ownership.
5    * The ASF licenses this file to You under the Apache License, Version 2.0
6    * (the "License"); you may not use this file except in compliance with
7    * the License.  You may obtain a copy of the License at
8    *
9    *      https://www.apache.org/licenses/LICENSE-2.0
10   *
11   * Unless required by applicable law or agreed to in writing, software
12   * distributed under the License is distributed on an "AS IS" BASIS,
13   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14   * See the License for the specific language governing permissions and
15   * limitations under the License.
16   */
17  package org.apache.commons.lang3.concurrent;
18  
19  import java.util.concurrent.CancellationException;
20  import java.util.concurrent.ConcurrentHashMap;
21  import java.util.concurrent.ConcurrentMap;
22  import java.util.concurrent.ExecutionException;
23  import java.util.concurrent.Future;
24  import java.util.function.Function;
25  
26  import org.apache.commons.lang3.exception.ExceptionUtils;
27  
28  /**
29   * Definition of an interface for a wrapper around a calculation that takes a single parameter and returns a result. The
30   * results for the calculation will be cached for future requests.
31   *
32   * <p>
33   * This is not a fully functional cache, there is no way of limiting or removing results once they have been generated.
34   * However, it is possible to get the implementation to regenerate the result for a given parameter, if an error was
35   * thrown during the previous calculation, by setting the option during the construction of the class. If this is not
36   * set the class will return the cached exception.
37   * </p>
38   * <p>
39   * Thanks go to Brian Goetz, Tim Peierls and the members of JCP JSR-166 Expert Group for coming up with the
40   * original implementation of the class. It was also published within Java Concurrency in Practice as a sample.
41   * </p>
42   *
43   * @param <I> the type of the input to the calculation
44   * @param <O> the type of the output of the calculation
45   * @since 3.6
46   */
47  public class Memoizer<I, O> implements Computable<I, O> {
48  
49      private final ConcurrentMap<I, Future<O>> cache = new ConcurrentHashMap<>();
50      private final Function<? super I, ? extends Future<O>> mappingFunction;
51      private final boolean recalculate;
52  
53      /**
54       * Constructs a Memoizer for the provided Computable calculation.
55       *
56       * <p>
57       * If a calculation throws an exception for any reason, this exception will be cached and returned for all future
58       * calls with the provided parameter.
59       * </p>
60       *
61       * @param computable the computation whose results should be memorized
62       */
63      public Memoizer(final Computable<I, O> computable) {
64          this(computable, false);
65      }
66  
67      /**
68       * Constructs a Memoizer for the provided Computable calculation, with the option of whether a Computation that
69       * experiences an error should recalculate on subsequent calls or return the same cached exception.
70       *
71       * @param computable the computation whose results should be memorized
72       * @param recalculate determines whether the computation should be recalculated on subsequent calls if the previous call
73       *        failed
74       */
75      public Memoizer(final Computable<I, O> computable, final boolean recalculate) {
76          this.recalculate = recalculate;
77          this.mappingFunction = k -> FutureTasks.run(() -> computable.compute(k));
78      }
79  
80      /**
81       * Constructs a Memoizer for the provided Function calculation.
82       *
83       * <p>
84       * If a calculation throws an exception for any reason, this exception will be cached and returned for all future
85       * calls with the provided parameter.
86       * </p>
87       *
88       * @param function the function whose results should be memorized
89       * @since 2.13.0
90       */
91      public Memoizer(final Function<I, O> function) {
92          this(function, false);
93      }
94  
95      /**
96       * Constructs a Memoizer for the provided Function calculation, with the option of whether a Function that
97       * experiences an error should recalculate on subsequent calls or return the same cached exception.
98       *
99       * @param function the computation whose results should be memorized
100      * @param recalculate determines whether the computation should be recalculated on subsequent calls if the previous call
101      *        failed
102      * @since 2.13.0
103      */
104      public Memoizer(final Function<I, O> function, final boolean recalculate) {
105         this.recalculate = recalculate;
106         this.mappingFunction = k -> FutureTasks.run(() -> function.apply(k));
107     }
108 
109     /**
110      * This method will return the result of the calculation and cache it, if it has not previously been calculated.
111      *
112      * <p>
113      * This cache will also cache exceptions that occur during the computation if the {@code recalculate} parameter in the
114      * constructor was set to {@code false}, or not set. Otherwise, if an exception happened on the previous calculation,
115      * the method will attempt again to generate a value.
116      * </p>
117      *
118      * @param arg the argument for the calculation
119      * @return the result of the calculation
120      * @throws InterruptedException thrown if the calculation is interrupted
121      */
122     @Override
123     public O compute(final I arg) throws InterruptedException {
124         while (true) {
125             final Future<O> future = cache.computeIfAbsent(arg, mappingFunction);
126             try {
127                 return future.get();
128             } catch (final CancellationException e) {
129                 cache.remove(arg, future);
130             } catch (final ExecutionException e) {
131                 if (recalculate) {
132                     cache.remove(arg, future);
133                 }
134                 throw launderException(e.getCause());
135             }
136         }
137     }
138 
139     /**
140      * This method launders a Throwable to either a RuntimeException, Error or any other Exception wrapped in an
141      * IllegalStateException.
142      *
143      * @param throwable the throwable to laundered
144      * @return a RuntimeException, Error or an IllegalStateException
145      */
146     private RuntimeException launderException(final Throwable throwable) {
147         throw new IllegalStateException("Unchecked exception", ExceptionUtils.throwUnchecked(throwable));
148     }
149 }