001/*
002 * Copyright (C) 2007 The Guava Authors
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
005 * in compliance with the License. You may obtain a copy of the License at
006 *
007 * http://www.apache.org/licenses/LICENSE-2.0
008 *
009 * Unless required by applicable law or agreed to in writing, software distributed under the License
010 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
011 * or implied. See the License for the specific language governing permissions and limitations under
012 * the License.
013 */
014
015package com.google.common.base;
016
017import com.google.common.annotations.GwtCompatible;
018import com.google.common.annotations.VisibleForTesting;
019import java.io.Serializable;
020import java.util.concurrent.TimeUnit;
021import org.checkerframework.checker.nullness.compatqual.NullableDecl;
022
023/**
024 * Useful suppliers.
025 *
026 * <p>All methods return serializable suppliers as long as they're given serializable parameters.
027 *
028 * @author Laurence Gonsalves
029 * @author Harry Heymann
030 * @since 2.0
031 */
032@GwtCompatible
033public final class Suppliers {
034  private Suppliers() {}
035
036  /**
037   * Returns a new supplier which is the composition of the provided function and supplier. In other
038   * words, the new supplier's value will be computed by retrieving the value from {@code supplier},
039   * and then applying {@code function} to that value. Note that the resulting supplier will not
040   * call {@code supplier} or invoke {@code function} until it is called.
041   */
042  public static <F, T> Supplier<T> compose(Function<? super F, T> function, Supplier<F> supplier) {
043    Preconditions.checkNotNull(function);
044    Preconditions.checkNotNull(supplier);
045    return new SupplierComposition<>(function, supplier);
046  }
047
048  private static class SupplierComposition<F, T> implements Supplier<T>, Serializable {
049    final Function<? super F, T> function;
050    final Supplier<F> supplier;
051
052    SupplierComposition(Function<? super F, T> function, Supplier<F> supplier) {
053      this.function = function;
054      this.supplier = supplier;
055    }
056
057    @Override
058    public T get() {
059      return function.apply(supplier.get());
060    }
061
062    @Override
063    public boolean equals(@NullableDecl Object obj) {
064      if (obj instanceof SupplierComposition) {
065        SupplierComposition<?, ?> that = (SupplierComposition<?, ?>) obj;
066        return function.equals(that.function) && supplier.equals(that.supplier);
067      }
068      return false;
069    }
070
071    @Override
072    public int hashCode() {
073      return Objects.hashCode(function, supplier);
074    }
075
076    @Override
077    public String toString() {
078      return "Suppliers.compose(" + function + ", " + supplier + ")";
079    }
080
081    private static final long serialVersionUID = 0;
082  }
083
084  /**
085   * Returns a supplier which caches the instance retrieved during the first call to {@code get()}
086   * and returns that value on subsequent calls to {@code get()}. See: <a
087   * href="http://en.wikipedia.org/wiki/Memoization">memoization</a>
088   *
089   * <p>The returned supplier is thread-safe. The delegate's {@code get()} method will be invoked at
090   * most once unless the underlying {@code get()} throws an exception. The supplier's serialized
091   * form does not contain the cached value, which will be recalculated when {@code get()} is called
092   * on the reserialized instance.
093   *
094   * <p>When the underlying delegate throws an exception then this memoizing supplier will keep
095   * delegating calls until it returns valid data.
096   *
097   * <p>If {@code delegate} is an instance created by an earlier call to {@code memoize}, it is
098   * returned directly.
099   */
100  public static <T> Supplier<T> memoize(Supplier<T> delegate) {
101    if (delegate instanceof NonSerializableMemoizingSupplier
102        || delegate instanceof MemoizingSupplier) {
103      return delegate;
104    }
105    return delegate instanceof Serializable
106        ? new MemoizingSupplier<T>(delegate)
107        : new NonSerializableMemoizingSupplier<T>(delegate);
108  }
109
110  @VisibleForTesting
111  static class MemoizingSupplier<T> implements Supplier<T>, Serializable {
112    final Supplier<T> delegate;
113    transient volatile boolean initialized;
114    // "value" does not need to be volatile; visibility piggy-backs
115    // on volatile read of "initialized".
116    @NullableDecl transient T value;
117
118    MemoizingSupplier(Supplier<T> delegate) {
119      this.delegate = Preconditions.checkNotNull(delegate);
120    }
121
122    @Override
123    public T get() {
124      // A 2-field variant of Double Checked Locking.
125      if (!initialized) {
126        synchronized (this) {
127          if (!initialized) {
128            T t = delegate.get();
129            value = t;
130            initialized = true;
131            return t;
132          }
133        }
134      }
135      return value;
136    }
137
138    @Override
139    public String toString() {
140      return "Suppliers.memoize(" + delegate + ")";
141    }
142
143    private static final long serialVersionUID = 0;
144  }
145
146  @VisibleForTesting
147  static class NonSerializableMemoizingSupplier<T> implements Supplier<T> {
148    volatile Supplier<T> delegate;
149    volatile boolean initialized;
150    // "value" does not need to be volatile; visibility piggy-backs
151    // on volatile read of "initialized".
152    @NullableDecl T value;
153
154    NonSerializableMemoizingSupplier(Supplier<T> delegate) {
155      this.delegate = Preconditions.checkNotNull(delegate);
156    }
157
158    @Override
159    public T get() {
160      // A 2-field variant of Double Checked Locking.
161      if (!initialized) {
162        synchronized (this) {
163          if (!initialized) {
164            T t = delegate.get();
165            value = t;
166            initialized = true;
167            // Release the delegate to GC.
168            delegate = null;
169            return t;
170          }
171        }
172      }
173      return value;
174    }
175
176    @Override
177    public String toString() {
178      return "Suppliers.memoize(" + delegate + ")";
179    }
180  }
181
182  /**
183   * Returns a supplier that caches the instance supplied by the delegate and removes the cached
184   * value after the specified time has passed. Subsequent calls to {@code get()} return the cached
185   * value if the expiration time has not passed. After the expiration time, a new value is
186   * retrieved, cached, and returned. See: <a
187   * href="http://en.wikipedia.org/wiki/Memoization">memoization</a>
188   *
189   * <p>The returned supplier is thread-safe. The supplier's serialized form does not contain the
190   * cached value, which will be recalculated when {@code get()} is called on the reserialized
191   * instance. The actual memoization does not happen when the underlying delegate throws an
192   * exception.
193   *
194   * <p>When the underlying delegate throws an exception then this memoizing supplier will keep
195   * delegating calls until it returns valid data.
196   *
197   * @param duration the length of time after a value is created that it should stop being returned
198   *     by subsequent {@code get()} calls
199   * @param unit the unit that {@code duration} is expressed in
200   * @throws IllegalArgumentException if {@code duration} is not positive
201   * @since 2.0
202   */
203  public static <T> Supplier<T> memoizeWithExpiration(
204      Supplier<T> delegate, long duration, TimeUnit unit) {
205    return new ExpiringMemoizingSupplier<T>(delegate, duration, unit);
206  }
207
208  @VisibleForTesting
209  static class ExpiringMemoizingSupplier<T> implements Supplier<T>, Serializable {
210    final Supplier<T> delegate;
211    final long durationNanos;
212    @NullableDecl transient volatile T value;
213    // The special value 0 means "not yet initialized".
214    transient volatile long expirationNanos;
215
216    ExpiringMemoizingSupplier(Supplier<T> delegate, long duration, TimeUnit unit) {
217      this.delegate = Preconditions.checkNotNull(delegate);
218      this.durationNanos = unit.toNanos(duration);
219      Preconditions.checkArgument(duration > 0);
220    }
221
222    @Override
223    public T get() {
224      // Another variant of Double Checked Locking.
225      //
226      // We use two volatile reads. We could reduce this to one by
227      // putting our fields into a holder class, but (at least on x86)
228      // the extra memory consumption and indirection are more
229      // expensive than the extra volatile reads.
230      long nanos = expirationNanos;
231      long now = Platform.systemNanoTime();
232      if (nanos == 0 || now - nanos >= 0) {
233        synchronized (this) {
234          if (nanos == expirationNanos) { // recheck for lost race
235            T t = delegate.get();
236            value = t;
237            nanos = now + durationNanos;
238            // In the very unlikely event that nanos is 0, set it to 1;
239            // no one will notice 1 ns of tardiness.
240            expirationNanos = (nanos == 0) ? 1 : nanos;
241            return t;
242          }
243        }
244      }
245      return value;
246    }
247
248    @Override
249    public String toString() {
250      // This is a little strange if the unit the user provided was not NANOS,
251      // but we don't want to store the unit just for toString
252      return "Suppliers.memoizeWithExpiration(" + delegate + ", " + durationNanos + ", NANOS)";
253    }
254
255    private static final long serialVersionUID = 0;
256  }
257
258  /** Returns a supplier that always supplies {@code instance}. */
259  public static <T> Supplier<T> ofInstance(@NullableDecl T instance) {
260    return new SupplierOfInstance<T>(instance);
261  }
262
263  private static class SupplierOfInstance<T> implements Supplier<T>, Serializable {
264    @NullableDecl final T instance;
265
266    SupplierOfInstance(@NullableDecl T instance) {
267      this.instance = instance;
268    }
269
270    @Override
271    public T get() {
272      return instance;
273    }
274
275    @Override
276    public boolean equals(@NullableDecl Object obj) {
277      if (obj instanceof SupplierOfInstance) {
278        SupplierOfInstance<?> that = (SupplierOfInstance<?>) obj;
279        return Objects.equal(instance, that.instance);
280      }
281      return false;
282    }
283
284    @Override
285    public int hashCode() {
286      return Objects.hashCode(instance);
287    }
288
289    @Override
290    public String toString() {
291      return "Suppliers.ofInstance(" + instance + ")";
292    }
293
294    private static final long serialVersionUID = 0;
295  }
296
297  /**
298   * Returns a supplier whose {@code get()} method synchronizes on {@code delegate} before calling
299   * it, making it thread-safe.
300   */
301  public static <T> Supplier<T> synchronizedSupplier(Supplier<T> delegate) {
302    return new ThreadSafeSupplier<T>(Preconditions.checkNotNull(delegate));
303  }
304
305  private static class ThreadSafeSupplier<T> implements Supplier<T>, Serializable {
306    final Supplier<T> delegate;
307
308    ThreadSafeSupplier(Supplier<T> delegate) {
309      this.delegate = delegate;
310    }
311
312    @Override
313    public T get() {
314      synchronized (delegate) {
315        return delegate.get();
316      }
317    }
318
319    @Override
320    public String toString() {
321      return "Suppliers.synchronizedSupplier(" + delegate + ")";
322    }
323
324    private static final long serialVersionUID = 0;
325  }
326
327  /**
328   * Returns a function that accepts a supplier and returns the result of invoking {@link
329   * Supplier#get} on that supplier.
330   *
331   * <p><b>Java 8 users:</b> use the method reference {@code Supplier::get} instead.
332   *
333   * @since 8.0
334   */
335  public static <T> Function<Supplier<T>, T> supplierFunction() {
336    @SuppressWarnings("unchecked") // implementation is "fully variant"
337    SupplierFunction<T> sf = (SupplierFunction<T>) SupplierFunctionImpl.INSTANCE;
338    return sf;
339  }
340
341  private interface SupplierFunction<T> extends Function<Supplier<T>, T> {}
342
343  private enum SupplierFunctionImpl implements SupplierFunction<Object> {
344    INSTANCE;
345
346    // Note: This makes T a "pass-through type"
347    @Override
348    public Object apply(Supplier<Object> input) {
349      return input.get();
350    }
351
352    @Override
353    public String toString() {
354      return "Suppliers.supplierFunction()";
355    }
356  }
357}