资讯专栏INFORMATION COLUMN

利用Guava的Suppliers.memoize实现单例

NickZhou / 747人阅读

本文主要介绍如何利用Guava的Suppliers.memoize实现单例。

实例
/**
 * 利用Suppliers.memoize实现单例
 * Created by xixicat on 15/12/25.
 */
public class SuppilerSingletonTest {

    class HeavyObject{
        public HeavyObject() {
            System.out.println("being created");
        }
    }

    class ObjectSuppiler implements Supplier{

        @Override
        public HeavyObject get() {
            return new HeavyObject();
        }
    }

    /**
     * 每次都new一次
     */
    @Test
    public void testNotSingleton(){
        Supplier notCached = new ObjectSuppiler();
        for(int i=0;i<5;i++){
            notCached.get();
        }
    }

    /**
     * 单例
     */
    @Test
    public void testSingleton(){
        Supplier notCached = new ObjectSuppiler();
        Supplier cachedSupplier = Suppliers.memoize(notCached);
        for(int i=0;i<5;i++){
            cachedSupplier.get();
        }
    }
}
Suppliers.memoize方法
/**
   * Returns a supplier which caches the instance retrieved during the first
   * call to {@code get()} and returns that value on subsequent calls to
   * {@code get()}. See:
   * memoization
   *
   * 

The returned supplier is thread-safe. The supplier"s serialized form * does not contain the cached value, which will be recalculated when {@code * get()} is called on the reserialized instance. * *

If {@code delegate} is an instance created by an earlier call to {@code * memoize}, it is returned directly. */ public static Supplier memoize(Supplier delegate) { return (delegate instanceof MemoizingSupplier) ? delegate : new MemoizingSupplier(Preconditions.checkNotNull(delegate)); } @VisibleForTesting static class MemoizingSupplier implements Supplier, Serializable { final Supplier 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 delegate) { this.delegate = 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; return t; } } } return value; } @Override public String toString() { return "Suppliers.memoize(" + delegate + ")"; } private static final long serialVersionUID = 0; }

参考

Guava Explained

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/65566.html

相关文章

  • [轮子系列]Google Guava之CharMatcher源码分析

    摘要:子类通过实现方法或重写其他父类的方法,从而提供了各种不同的具体操作,如判断是否为某一个字符,判断是否为数字字符,判断是否为字符等。 showImg(https://segmentfault.com/img/bVbe1IW?w=300&h=300); 本文源地址:http://www.fullstackyang.com/...,转发请注明该地址或segmentfault地址,谢谢! 最近...

    pekonchan 评论0 收藏0
  • Guava-Optional(译)

    摘要:创建一个指定引用的,若引用为则表示引用缺失,并返回一个。返回包含的实例,该实例必须存在,如果不存在将会抛出异常。说明有三个方法没有作解释,主要是担心相关知识不理解,容易做出错误的翻译,望请谅解 原文地址译者 Guava Optional Class Optional 是一个不可变对象,用来包含一个非null对象。Optional使用absent来表达null值。该类提供了很多实用的方法...

    nifhlheimr 评论0 收藏0
  • Guava 源码分析(Cache 原理)

    摘要:缓存本次主要讨论缓存。清除数据时的回调通知。具体不在本次的讨论范围。应该是以下原因新起线程需要资源消耗。维护过期数据还要获取额外的锁,增加了消耗。 showImg(https://segmentfault.com/img/remote/1460000015272232); 前言 Google 出的 Guava 是 Java 核心增强的库,应用非常广泛。 我平时用的也挺频繁,这次就借助日...

    wangxinarhat 评论0 收藏0
  • Guava 源码分析(Cache 原理)

    摘要:缓存本次主要讨论缓存。清除数据时的回调通知。具体不在本次的讨论范围。应该是以下原因新起线程需要资源消耗。维护过期数据还要获取额外的锁,增加了消耗。 showImg(https://segmentfault.com/img/remote/1460000015272232); 前言 Google 出的 Guava 是 Java 核心增强的库,应用非常广泛。 我平时用的也挺频繁,这次就借助日...

    Thanatos 评论0 收藏0

发表评论

0条评论

最新活动
阅读需要支付1元查看
<