lang3 系列之 Concurrent 包 ① 延迟初始化LazyInitializer

lang3的LazyInitializer提供了类的延迟初始化功能,并且获取对象的时候是线程安全的,也是单例的。

先看下官方的声明:

This class provides a generic implementation of the lazy initialization pattern.
该类提供了延迟初始化模式的通用实现。

Sometimes an application has to deal with an object only under certain circumstances, e.g. when the user selects a specific menu item or if a special event is received. If the creation of the object is costly or the consumption of memory or other system resources is significant, it may make sense to defer the creation of this object until it is really needed. This is a use case for the lazy initialization pattern.
有时,应用程序必须仅在某些情况下处理对象,例如当用户选择特定菜单项或收到特殊事件时。如果对象的创建成本高或者内存或其他系统资源的消耗很大,那么推迟创建此对象直到真正需要它才有意义。这是延迟初始化模式的用例。

也就是说,用到比较重量级的类的时候,恰到好处。
该类只有两个方法:T get() 和 T initialize(),见名知意,用来获取对象和初始化对象。

T get() 源码:
   @Override
    public T get() throws ConcurrentException {
        // use a temporary variable to reduce the number of reads of the
        // volatile field
        T result = object;
        if (result == NO_INIT) {
            synchronized (this) {
                result = object;
                if (result == NO_INIT) {
                    object = result = initialize();
                }
            }
        }
        return result;
    }

在获取对象的时候,会先与本地的NO_INIT比较,NO_INIT就是你实例化的对象的副本,默认是new Object(),如果result不是你的对象,也就是没有实例化过,则执行initialize()初始化对象。

T initialize()是来自ConcurrentInitializer接口,是我们要实现的方法
 protected abstract T initialize() throws ConcurrentException;

是用来初始化我们的对象的。

实例:
public class Person {

    private String name;
    private int age;

    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    @Override
    public String toString() {
        return this.getName() + " " + this.getAge();
    }
}
public class LazyInitializerDemo extends LazyInitializer {
    @Override
    protected Person initialize() throws ConcurrentException {
        Person person = new Person();
        person.setAge(18);
        person.setName("xingmin");
        return person;
    }

    @Test
    public void test() throws ConcurrentException {
        Person person = new LazyInitializerDemo().get();
        System.out.println(person.toString());//xingmin 18
    }
}

你可能感兴趣的:(lang3 系列之 Concurrent 包 ① 延迟初始化LazyInitializer)