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 javax.annotation.Nullable; 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(@Nullable 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 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 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 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 /** 259 * Returns a supplier that always supplies {@code instance}. 260 */ 261 public static <T> Supplier<T> ofInstance(@Nullable T instance) { 262 return new SupplierOfInstance<T>(instance); 263 } 264 265 private static class SupplierOfInstance<T> implements Supplier<T>, Serializable { 266 final T instance; 267 268 SupplierOfInstance(@Nullable T instance) { 269 this.instance = instance; 270 } 271 272 @Override 273 public T get() { 274 return instance; 275 } 276 277 @Override 278 public boolean equals(@Nullable Object obj) { 279 if (obj instanceof SupplierOfInstance) { 280 SupplierOfInstance<?> that = (SupplierOfInstance<?>) obj; 281 return Objects.equal(instance, that.instance); 282 } 283 return false; 284 } 285 286 @Override 287 public int hashCode() { 288 return Objects.hashCode(instance); 289 } 290 291 @Override 292 public String toString() { 293 return "Suppliers.ofInstance(" + instance + ")"; 294 } 295 296 private static final long serialVersionUID = 0; 297 } 298 299 /** 300 * Returns a supplier whose {@code get()} method synchronizes on {@code delegate} before calling 301 * it, making it thread-safe. 302 */ 303 public static <T> Supplier<T> synchronizedSupplier(Supplier<T> delegate) { 304 return new ThreadSafeSupplier<T>(Preconditions.checkNotNull(delegate)); 305 } 306 307 private static class ThreadSafeSupplier<T> implements Supplier<T>, Serializable { 308 final Supplier<T> delegate; 309 310 ThreadSafeSupplier(Supplier<T> delegate) { 311 this.delegate = delegate; 312 } 313 314 @Override 315 public T get() { 316 synchronized (delegate) { 317 return delegate.get(); 318 } 319 } 320 321 @Override 322 public String toString() { 323 return "Suppliers.synchronizedSupplier(" + delegate + ")"; 324 } 325 326 private static final long serialVersionUID = 0; 327 } 328 329 /** 330 * Returns a function that accepts a supplier and returns the result of invoking {@link 331 * Supplier#get} on that supplier. 332 * 333 * <p><b>Java 8 users:</b> use the method reference {@code Supplier::get} instead. 334 * 335 * @since 8.0 336 */ 337 public static <T> Function<Supplier<T>, T> supplierFunction() { 338 @SuppressWarnings("unchecked") // implementation is "fully variant" 339 SupplierFunction<T> sf = (SupplierFunction<T>) SupplierFunctionImpl.INSTANCE; 340 return sf; 341 } 342 343 private interface SupplierFunction<T> extends Function<Supplier<T>, T> {} 344 345 private enum SupplierFunctionImpl implements SupplierFunction<Object> { 346 INSTANCE; 347 348 // Note: This makes T a "pass-through type" 349 @Override 350 public Object apply(Supplier<Object> input) { 351 return input.get(); 352 } 353 354 @Override 355 public String toString() { 356 return "Suppliers.supplierFunction()"; 357 } 358 } 359}