Java单例模式

饿汉模式:

/**
 * 单例-饿汉模式(即静态创建)
 * 优点:线程安全,实现简单
 * 缺点:SingleInstance 在类加载的时候就实例化了,即便不用。(如果不用的话会造成内存浪费)
 * @author Rambo(浩祥)
 * @create 2017-09-21
 **/
public final class SingleInstance1 {
    private static SingleInstance1 singleInstance = new SingleInstance1();

    private SingleInstance1(){}

    public static SingleInstance1 getSingleInstance(){
        return singleInstance;
    }
}

懒汉模式1

/**
 * 单例--懒汉模式1(即用到的时候再去创建)
 * 优点:不用场景下,比懒汉模式节省内存
 * 缺点:非线程安全,耗时比懒汉模式长
 * @author Rambo(浩祥)
 * @create 2017-08-25
 **/
public final class SingleInstance2 {

    private static SingleInstance2 singleInstance = null;

    private SingleInstance2(){

    }

    public static SingleInstance2 getSingleInstance(){
        try {
            if (singleInstance == null){
                // 休眠50ms构造线程非安全的场景
                Thread.sleep(50);
                singleInstance = new SingleInstance2();
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return singleInstance;
    }
}

懒汉模式2

/**
 * 单例-懒汉模式2
 * 优点:较懒汉模式1比线程安全
 * 缺点:较懒汉模式1耗时,因为要进行线程同步
 * @author Rambo(浩祥)
 * @create 2017-09-21
 **/
public class SingleInstance3 {
    private static SingleInstance3 singleInstance = null;

    private SingleInstance3(){

    }

    public static synchronized SingleInstance3 getSingleInstance(){
        try {
            if (singleInstance == null){
                // 休眠50ms构造线程非安全的场景
                Thread.sleep(50);
                singleInstance = new SingleInstance3();
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return singleInstance;
    }
}

懒汉模式3

/**
 * 单例-懒汉模式3
 * 优点-线程安全,比懒汉模式2节约用时
 * @author Rambo(浩祥)
 * @create 2017-09-21
 **/
public class SingleInstance4 {
    private static SingleInstance4 singleInstance = null;

    private SingleInstance4(){

    }

    public static SingleInstance4 getSingleInstance(){
        try {
            if (singleInstance == null){
                // 休眠50ms构造线程非安全的场景
                Thread.sleep(50);
                synchronized (SingleInstance4.class){
                    if (singleInstance == null){
                        singleInstance = new SingleInstance4();
                    }
                }
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return singleInstance;
    }
}

懒汉模式4

/**
 * 单例-懒汉模式4
 *
 * @author Rambo(浩祥)
 * @create 2017-09-21
 **/
public class SingleInstance5 {
    private static class GetInstance{
        private static SingleInstance5 singleInstance = new SingleInstance5();
    }
    private SingleInstance5(){

    }
    // 只有调用到该方法是GetInstance才会加载,singleInstance才会初始化
    public static SingleInstance5 getSingleInstance(){
        return GetInstance.singleInstance;
    }
}

测试程序

验证不同单例模式的实例获取时间、内存占用、线程安全等

import com.rambo.memory.MemoryCounter;

/**
 * @author Rambo(浩祥)
 * @create 2017-03-09
 **/
public class Practice {
    // MemoryCounter是自己写的对象内存的计算类
    private static MemoryCounter memoryCounter = new MemoryCounter();

    public static void main(String[] args) {

        Thread getInstanceThread = new Thread(new Runnable() {
            @Override
            public void run() {
                getInstance();
            }
        });
        getInstanceThread.start();

        Thread getInstanceThread2 = new Thread(new Runnable() {
            @Override
            public void run() {
                getInstance();
            }
        });
        getInstanceThread2.start();
    }

    private static void getInstance() {
        long startTime = System.currentTimeMillis();
//        SingleInstance1 singleInstance1 = SingleInstance1.getSingleInstance();
//        System.out.println(Thread.currentThread().getName() + ":singleInstance1获取对象消耗用时:" + (System.currentTimeMillis() - startTime));
//        System.out.println(Thread.currentThread().getName() + ":singleInstance1对象hashCode:" + Integer.toString(singleInstance1.hashCode()));
//        System.out.println(Thread.currentThread().getName() + ":singleInstance1线程对象大小:" + memoryCounter.estimate(singleInstance1));

//        SingleInstance2 singleInstance2 = SingleInstance2.getSingleInstance();
//        System.out.println(Thread.currentThread().getName() + ":singleInstance2获取对象消耗用时:" + (System.currentTimeMillis() - startTime));
//        System.out.println(Thread.currentThread().getName() + ":singleInstance2对象hashCode:" + Integer.toString(singleInstance2.hashCode()));
//        System.out.println(Thread.currentThread().getName() + ":singleInstance2线程对象大小:" + memoryCounter.estimate(singleInstance2));
//
//        SingleInstance3 singleInstance3 = SingleInstance3.getSingleInstance();
//        System.out.println(Thread.currentThread().getName() + ":singleInstance3获取对象消耗用时:" + (System.currentTimeMillis() - startTime));
//        System.out.println(Thread.currentThread().getName() + ":singleInstance3对象hashCode:" + Integer.toString(singleInstance3.hashCode()));
//        System.out.println(Thread.currentThread().getName() + ":singleInstance3线程对象大小:" + memoryCounter.estimate(singleInstance3));
//
//        SingleInstance4 singleInstance4 = SingleInstance4.getSingleInstance();
//        System.out.println(Thread.currentThread().getName() + ":singleInstance4获取对象消耗用时:" + (System.currentTimeMillis() - startTime));
//        System.out.println(Thread.currentThread().getName() + ":singleInstance4对象hashCode:" + Integer.toString(singleInstance4.hashCode()));
//        System.out.println(Thread.currentThread().getName() + ":singleInstance4线程对象大小:" + memoryCounter.estimate(singleInstance4));
//
        SingleInstance5 singleInstance5 = SingleInstance5.getSingleInstance();
        System.out.println(Thread.currentThread().getName() + ":singleInstance5获取对象消耗用时:" + (System.currentTimeMillis() - startTime));
        System.out.println(Thread.currentThread().getName() + ":singleInstance5对象hashCode:" + Integer.toString(singleInstance5.hashCode()));
        System.out.println(Thread.currentThread().getName() + ":singleInstance5线程对象大小:" + memoryCounter.estimate(singleInstance5));
    }
}

运行结果如下:

饿汉
Java单例模式_第1张图片
懒汉1,非线程安全
Java单例模式_第2张图片
懒汉2
Java单例模式_第3张图片
懒汉3
Java单例模式_第4张图片
懒汉4

注:耗时大于50的是因为加了sleep(50)模拟线程非安全
注:实际应用建议应用懒汉4的方式

你可能感兴趣的:(Java单例模式)