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<F, T>(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: 087 * <a 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. The supplier's serialized form does not contain the cached value, which will be 091 * recalculated when {@code get()} is called on the reserialized instance. 092 * 093 * <p>If {@code delegate} is an instance created by an earlier call to {@code 094 * memoize}, it is returned directly. 095 */ 096 public static <T> Supplier<T> memoize(Supplier<T> delegate) { 097 return (delegate instanceof MemoizingSupplier) 098 ? delegate 099 : new MemoizingSupplier<T>(Preconditions.checkNotNull(delegate)); 100 } 101 102 @VisibleForTesting 103 static class MemoizingSupplier<T> implements Supplier<T>, Serializable { 104 final Supplier<T> delegate; 105 transient volatile boolean initialized; 106 // "value" does not need to be volatile; visibility piggy-backs 107 // on volatile read of "initialized". 108 transient T value; 109 110 MemoizingSupplier(Supplier<T> delegate) { 111 this.delegate = delegate; 112 } 113 114 @Override 115 public T get() { 116 // A 2-field variant of Double Checked Locking. 117 if (!initialized) { 118 synchronized (this) { 119 if (!initialized) { 120 T t = delegate.get(); 121 value = t; 122 initialized = true; 123 return t; 124 } 125 } 126 } 127 return value; 128 } 129 130 @Override 131 public String toString() { 132 return "Suppliers.memoize(" + delegate + ")"; 133 } 134 135 private static final long serialVersionUID = 0; 136 } 137 138 /** 139 * Returns a supplier that caches the instance supplied by the delegate and removes the cached 140 * value after the specified time has passed. Subsequent calls to {@code get()} return the cached 141 * value if the expiration time has not passed. After the expiration time, a new value is 142 * retrieved, cached, and returned. See: 143 * <a href="http://en.wikipedia.org/wiki/Memoization">memoization</a> 144 * 145 * <p>The returned supplier is thread-safe. The supplier's serialized form does not contain the 146 * cached value, which will be recalculated when {@code 147 * get()} is called on the reserialized instance. 148 * 149 * @param duration the length of time after a value is created that it should stop being returned 150 * by subsequent {@code get()} calls 151 * @param unit the unit that {@code duration} is expressed in 152 * @throws IllegalArgumentException if {@code duration} is not positive 153 * @since 2.0 154 */ 155 public static <T> Supplier<T> memoizeWithExpiration( 156 Supplier<T> delegate, long duration, TimeUnit unit) { 157 return new ExpiringMemoizingSupplier<T>(delegate, duration, unit); 158 } 159 160 @VisibleForTesting 161 static class ExpiringMemoizingSupplier<T> implements Supplier<T>, Serializable { 162 final Supplier<T> delegate; 163 final long durationNanos; 164 transient volatile T value; 165 // The special value 0 means "not yet initialized". 166 transient volatile long expirationNanos; 167 168 ExpiringMemoizingSupplier(Supplier<T> delegate, long duration, TimeUnit unit) { 169 this.delegate = Preconditions.checkNotNull(delegate); 170 this.durationNanos = unit.toNanos(duration); 171 Preconditions.checkArgument(duration > 0); 172 } 173 174 @Override 175 public T get() { 176 // Another variant of Double Checked Locking. 177 // 178 // We use two volatile reads. We could reduce this to one by 179 // putting our fields into a holder class, but (at least on x86) 180 // the extra memory consumption and indirection are more 181 // expensive than the extra volatile reads. 182 long nanos = expirationNanos; 183 long now = Platform.systemNanoTime(); 184 if (nanos == 0 || now - nanos >= 0) { 185 synchronized (this) { 186 if (nanos == expirationNanos) { // recheck for lost race 187 T t = delegate.get(); 188 value = t; 189 nanos = now + durationNanos; 190 // In the very unlikely event that nanos is 0, set it to 1; 191 // no one will notice 1 ns of tardiness. 192 expirationNanos = (nanos == 0) ? 1 : nanos; 193 return t; 194 } 195 } 196 } 197 return value; 198 } 199 200 @Override 201 public String toString() { 202 // This is a little strange if the unit the user provided was not NANOS, 203 // but we don't want to store the unit just for toString 204 return "Suppliers.memoizeWithExpiration(" + delegate + ", " + durationNanos + ", NANOS)"; 205 } 206 207 private static final long serialVersionUID = 0; 208 } 209 210 /** 211 * Returns a supplier that always supplies {@code instance}. 212 */ 213 public static <T> Supplier<T> ofInstance(@Nullable T instance) { 214 return new SupplierOfInstance<T>(instance); 215 } 216 217 private static class SupplierOfInstance<T> implements Supplier<T>, Serializable { 218 final T instance; 219 220 SupplierOfInstance(@Nullable T instance) { 221 this.instance = instance; 222 } 223 224 @Override 225 public T get() { 226 return instance; 227 } 228 229 @Override 230 public boolean equals(@Nullable Object obj) { 231 if (obj instanceof SupplierOfInstance) { 232 SupplierOfInstance<?> that = (SupplierOfInstance<?>) obj; 233 return Objects.equal(instance, that.instance); 234 } 235 return false; 236 } 237 238 @Override 239 public int hashCode() { 240 return Objects.hashCode(instance); 241 } 242 243 @Override 244 public String toString() { 245 return "Suppliers.ofInstance(" + instance + ")"; 246 } 247 248 private static final long serialVersionUID = 0; 249 } 250 251 /** 252 * Returns a supplier whose {@code get()} method synchronizes on {@code delegate} before calling 253 * it, making it thread-safe. 254 */ 255 public static <T> Supplier<T> synchronizedSupplier(Supplier<T> delegate) { 256 return new ThreadSafeSupplier<T>(Preconditions.checkNotNull(delegate)); 257 } 258 259 private static class ThreadSafeSupplier<T> implements Supplier<T>, Serializable { 260 final Supplier<T> delegate; 261 262 ThreadSafeSupplier(Supplier<T> delegate) { 263 this.delegate = delegate; 264 } 265 266 @Override 267 public T get() { 268 synchronized (delegate) { 269 return delegate.get(); 270 } 271 } 272 273 @Override 274 public String toString() { 275 return "Suppliers.synchronizedSupplier(" + delegate + ")"; 276 } 277 278 private static final long serialVersionUID = 0; 279 } 280 281 /** 282 * Returns a function that accepts a supplier and returns the result of invoking {@link 283 * Supplier#get} on that supplier. 284 * 285 * <p><b>Java 8 users:</b> use the method reference {@code Supplier::get} instead. 286 * 287 * @since 8.0 288 */ 289 public static <T> Function<Supplier<T>, T> supplierFunction() { 290 @SuppressWarnings("unchecked") // implementation is "fully variant" 291 SupplierFunction<T> sf = (SupplierFunction<T>) SupplierFunctionImpl.INSTANCE; 292 return sf; 293 } 294 295 private interface SupplierFunction<T> extends Function<Supplier<T>, T> {} 296 297 private enum SupplierFunctionImpl implements SupplierFunction<Object> { 298 INSTANCE; 299 300 // Note: This makes T a "pass-through type" 301 @Override 302 public Object apply(Supplier<Object> input) { 303 return input.get(); 304 } 305 306 @Override 307 public String toString() { 308 return "Suppliers.supplierFunction()"; 309 } 310 } 311}