Guava Supplier实例

今天想讲一下Guava Suppliers的几点用法。Guava Suppliers的主要功能是创建包裹的单例对象,通过get方法可以获取对象的值。每次获取的对象都为同一个对象,但你和单例模式有所区别,Suppliers具备更加迷人的色彩。本文会通过几个实例来讲解Guava Suppliers的一些特性。

Code Test Case

Lazy初始化,Supplier wrapped的对象只在第一次get时候会被初始化

    @Test
    public void should_init_the_supplier_wrapped_object_when_get_object() throws Exception {
        Supplier<Integer> memoize = Suppliers.memoize(new Supplier<Integer>() {
            public Integer get() {
                System.out.println("init supplier wrapped object");
                return 1;
            }
        });
        System.out.println("main thread block");
        Thread.sleep(2000);
        System.out.println(memoize.get());
    }

Supplier wrapped对象只初始化一次

    @Test
    public void should_init_the_supplier_wrapped_object_for_only_one_time() throws Exception {
        Supplier<Integer> memoize = Suppliers.memoize(new Supplier<Integer>() {
            public Integer get() {
                System.out.println("init supplier wrapped object");
                return 1;
            }
        });
        System.out.println(memoize.get());
        System.out.println(memoize.get());
    }

可以使用memoizeWithExpiration函数创建过期设置的Supplier对象,时间过期,get对象会重新初始化对象

    @Test
    public void should_re_init_the_supplier_wrapped_object_when_set_the_expire_time() throws Exception {
        Supplier<Integer> memoize = Suppliers.memoizeWithExpiration(new Supplier<Integer>() {
            public Integer get() {
                System.out.println("init supplier wrapped object");
                return 1;
            }
        }, 5, TimeUnit.SECONDS);

        System.out.println(memoize.get());
        Thread.sleep(6000);
        System.out.println(memoize.get());
    }

Conclsion

Suppliers的特性可以用来对程序中只需要初始化一次的资源进行管理,比如数据库管理对象,当然,用户也可以根据需求选择是否需要定时更新对象,总而言之,Suppliers给我们编程带来了更多的选择。

今天是国庆节,祝愿大家国庆七天乐,玩的开心:)

原文地址:https://www.cnblogs.com/jun-ma/p/4850591.html