Supplier
Guava Functional中的Supplier是通过给定的类型返回一个对象或者创建对象,即用作创建对象。
package com.google.common.base;
@GwtCompatible
@FunctionalInterface
public interface Supplier<T> extends java.util.function.Supplier<T> {
@CanIgnoreReturnValue
T get();
}
Suppliers类,Supplier接口的默认实现类,主要关注get方法。
package com.google.common.base;
@GwtCompatible
public final class Suppliers {
private Suppliers() {}
/**
* 传入一个Guava function<F, T>与supplier<F>,将supplier.get的F变量通过function返回T
* 使用(以匿名类演示,也可以使用lambda实现):
* Suppliers.compose(new Function<String, Integer>() {
* @Nullable
* @Override
* public Integer apply(@Nullable String input) {
* Preconditions.checkNotNull(input);
* return input.length();
* }
* }, new Supplier<String>() {
* @Override
* public String get() {
* return "xucc";
* }
* });
*/
public static <F, T> Supplier<T> compose(Function<? super F, T> function, Supplier<F> supplier) {
// function、supplier为null抛出NullPointerException异常
Preconditions.checkNotNull(function);
Preconditions.checkNotNull(supplier);
return new SupplierComposition<F, T>(function, supplier);
}
private static class SupplierComposition<F, T> implements Supplier<T>, Serializable {
final Function<? super F, T> function;
final Supplier<F> supplier;
SupplierComposition(Function<? super F, T> function, Supplier<F> supplier) {
this.function = function;
this.supplier = supplier;
}
@Override
public T get() {
// 类型转换
return function.apply(supplier.get());
}
@Override
public boolean equals(@Nullable Object obj) {
if (obj instanceof SupplierComposition) {
SupplierComposition<?, ?> that = (SupplierComposition<?, ?>) obj;
return function.equals(that.function) &&
supplier.equals(that.supplier);
}
return false;
}
@Override
public int hashCode() {
return Objects.hashCode(function, supplier);
}
@Override
public String toString() {
return "Suppliers.compose(" + function + ", " + supplier + ")";
}
private static final long serialVersionUID = 0;
}
/**
* 备忘录
* 缓存一个对象,以单例的形式存在
* String name = Suppliers.memoize(() -> "xucc").get();
*/
public static <T> Supplier<T> memoize(Supplier<T> delegate) {
if (delegate instanceof NonSerializableMemoizingSupplier
|| delegate instanceof MemoizingSupplier) {
return delegate;
}
// 传入的对象是否实现了序列化,创建不同的Supplier实现类
return delegate instanceof Serializable
? new MemoizingSupplier<T>(delegate)
: new NonSerializableMemoizingSupplier<T>(delegate);
}
// 序列化备忘录,构造时传入Supplier,因为initialized使用了transient、volatile修饰,
// 所以即使Suppliers序列化之后,get的值也不会变。
@VisibleForTesting
static class MemoizingSupplier<T> implements Supplier<T>, Serializable {
final Supplier<T> delegate;
transient volatile boolean initialized;
// "value" does not need to be volatile; visibility piggy-backs
// on volatile read of "initialized".
transient T value;
MemoizingSupplier(Supplier<T> delegate) {
this.delegate = Preconditions.checkNotNull(delegate);
}
@Override
public T get() {
// A 2-field variant of Double Checked Locking.
// 双重加锁,第一次initialized为false
if (!initialized) {
// 加锁
synchronized (this) {
if (!initialized) {
T t = delegate.get();
value = t;
// 修改initialized,以后get只会获得第一次的value
initialized = true;
return t;
}
}
}
return value;
}
@Override
public String toString() {
return "Suppliers.memoize(" + delegate + ")";
}
private static final long serialVersionUID = 0;
}
// 非序列化备忘录,在get里会将delegate置空,且initialized不被transient修饰,
// 当Suppliers序列化之后,get的值可以变化
@VisibleForTesting
static class NonSerializableMemoizingSupplier<T> implements Supplier<T> {
volatile Supplier<T> delegate;
volatile boolean initialized;
// "value" does not need to be volatile; visibility piggy-backs
// on volatile read of "initialized".
T value;
NonSerializableMemoizingSupplier(Supplier<T> delegate) {
this.delegate = Preconditions.checkNotNull(delegate);
}
@Override
public T get() {
// A 2-field variant of Double Checked Locking.
if (!initialized) {
synchronized (this) {
if (!initialized) {
T t = delegate.get();
value = t;
initialized = true;
// Release the delegate to GC.
// 使用过一次delegate变为null,下次可以传入别的delegate来进行get
delegate = null;
return t;
}
}
}
return value;
}
@Override
public String toString() {
return "Suppliers.memoize(" + delegate + ")";
}
}
/**
* 设置过期时间的备忘录
* memoizeWithExpiration方法与memoize方法工作相同,只不过缓存的对象超过了过期时间duration
* 就会返回真实Supplier实例get方法返回的值,在给定的时间当中缓存并且返回Supplier包装对象。
* 注意这个实例的缓存不是物理缓存,包装后的Supplier对象当中有真实Supplier对象的值
*/
public static <T> Supplier<T> memoizeWithExpiration(
Supplier<T> delegate, long duration, TimeUnit unit) {
// 传入创建memoize的delegate,以及过期时间duration和时间单位unit
return new ExpiringMemoizingSupplier<T>(delegate, duration, unit);
}
@VisibleForTesting
static class ExpiringMemoizingSupplier<T> implements Supplier<T>, Serializable {
final Supplier<T> delegate;
final long durationNanos;
transient volatile T value;
// The special value 0 means "not yet initialized".
transient volatile long expirationNanos;
ExpiringMemoizingSupplier(Supplier<T> delegate, long duration, TimeUnit unit) {
this.delegate = Preconditions.checkNotNull(delegate);
this.durationNanos = unit.toNanos(duration);
Preconditions.checkArgument(duration > 0);
}
@Override
public T get() {
// Another variant of Double Checked Locking.
//
// We use two volatile reads. We could reduce this to one by
// putting our fields into a holder class, but (at least on x86)
// the extra memory consumption and indirection are more
// expensive than the extra volatile reads.
long nanos = expirationNanos;
long now = Platform.systemNanoTime();
if (nanos == 0 || now - nanos >= 0) {
synchronized (this) {
if (nanos == expirationNanos) { // recheck for lost race
T t = delegate.get();
value = t;
nanos = now + durationNanos;
// In the very unlikely event that nanos is 0, set it to 1;
// no one will notice 1 ns of tardiness.
expirationNanos = (nanos == 0) ? 1 : nanos;
return t;
}
}
}
return value;
}
@Override
public String toString() {
// This is a little strange if the unit the user provided was not NANOS,
// but we don't want to store the unit just for toString
return "Suppliers.memoizeWithExpiration(" + delegate + ", " + durationNanos + ", NANOS)";
}
private static final long serialVersionUID = 0;
}
/**
* 返回传入的实例
*/
public static <T> Supplier<T> ofInstance(@Nullable T instance) {
return new SupplierOfInstance<T>(instance);
}
private static class SupplierOfInstance<T> implements Supplier<T>, Serializable {
final T instance;
SupplierOfInstance(@Nullable T instance) {
this.instance = instance;
}
@Override
public T get() {
return instance;
}
@Override
public boolean equals(@Nullable Object obj) {
if (obj instanceof SupplierOfInstance) {
SupplierOfInstance<?> that = (SupplierOfInstance<?>) obj;
return Objects.equal(instance, that.instance);
}
return false;
}
@Override
public int hashCode() {
return Objects.hashCode(instance);
}
@Override
public String toString() {
return "Suppliers.ofInstance(" + instance + ")";
}
private static final long serialVersionUID = 0;
}
/**
* 返回一个线程安全的Supplier
*/
public static <T> Supplier<T> synchronizedSupplier(Supplier<T> delegate) {
return new ThreadSafeSupplier<T>(Preconditions.checkNotNull(delegate));
}
private static class ThreadSafeSupplier<T> implements Supplier<T>, Serializable {
final Supplier<T> delegate;
ThreadSafeSupplier(Supplier<T> delegate) {
this.delegate = delegate;
}
@Override
public T get() {
synchronized (delegate) {
return delegate.get();
}
}
@Override
public String toString() {
return "Suppliers.synchronizedSupplier(" + delegate + ")";
}
private static final long serialVersionUID = 0;
}
/**
* 使用Supplier模拟一个Function
*/
public static <T> Function<Supplier<T>, T> supplierFunction() {
@SuppressWarnings("unchecked") // implementation is "fully variant"
SupplierFunction<T> sf = (SupplierFunction<T>) SupplierFunctionImpl.INSTANCE;
return sf;
}
private interface SupplierFunction<T> extends Function<Supplier<T>, T> {}
private enum SupplierFunctionImpl implements SupplierFunction<Object> {
INSTANCE;
// Note: This makes T a "pass-through type"
@Override
public Object apply(Supplier<Object> input) {
// Supplier作为Function的输入,Supplier.get作为Function的输出
return input.get();
}
@Override
public String toString() {
return "Suppliers.supplierFunction()";
}
}
}