饿汉模式
懒汉模式
多线程加锁synchronized
双重检查
反序列化readResolve
防止多线程重排序volatile

 

饿汉模式:

public class MySingleton {
	private MySingleton() {};
	private static final volatile MySingleton instance = new MySingleton();
	public static MySingleton getInstance() {
		return instance;
	}
	private Object readResolve() {
		return instance;
	}
}

 

懒汉模式:

public class MySingleton {
	private MySingleton() {};
	private static final volatile MySingleton instance = null;
	public static MySingleton getInstance() {
		if (null == instance) {
			synchronized(MySingleton.class) {
				if (null == instance) {
					instance = new MySingleton();
				}
			}
		}
		return instance;
	}
	private Object readResolve() {
		return instance;
	}
}

 

测试代码:

public class MySingletonTest {

    @Test
    public void test() throws Exception{
        MySingleton mySingleton1 = null;
        MySingleton mySingleton = MySingleton.getInstance();

        FileOutputStream fos = new FileOutputStream("mySingleton.txt");
        ObjectOutputStream oos = new ObjectOutputStream(fos);
        oos.writeObject(mySingleton);
        oos.flush();
        oos.close();

        FileInputStream fis = new FileInputStream("mySingleton.txt");
        ObjectInputStream ois = new ObjectInputStream(fis);
        mySingleton1 = (MySingleton) ois.readObject();

        Assert.assertEquals(mySingleton, mySingleton1);
    }
}

 

最后修改于 2019-09-18 17:12:32
如果觉得我的文章对你有用,请随意赞赏
扫一扫支付
上一篇