Java使用延迟初始化

来源:互联网 发布:电脑技术员必备软件 编辑:程序博客网 时间:2024/06/05 18:23

延迟初始化应当使用到那些第一次使用采用初始化的值上,如果不使用则永远不需要初始化;大多数值都应当在正常初始化

1. 使用同步访问方法

private String str;synchronized String getStr() {    if (str == null) {        str = "Lazy Initialization";    }    return str;}

2. 使用holder class 模式

public class Test {    private static class StringHolder {        static final String str = "Holder Class";    }    public String getStr() {        return StringHolder.str;    }}

3. 使用双重检查模式

public class Test {    private volatile String str;    public String getStr() {        if (str == null) {// 第一次检查            synchronized(this) {// 加锁                if(str == null) {// 第二次检查                    str = "Hello World!";                }            }        }    }}
第一次写博客,必须做一个记号标记
1 0