Guava Supplier&Suppliers 源碼分析

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()";
        }
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章