Java单例模式的几种写法

《Java并发编程 从入门到精通》读书笔记。

错误模式

class Test{

    private static Test instance;
    privae Test(){}

    public static Test getInstance(){
        if(null==instance)
            instance = new Test();
        return instance;
    }
}

低效模式:synchronized

class Test{

    private static Test instance;
    private Test(){}

    public static synchronized Test getInstance(){
        if(null==instance)
            instance = new Test();
        return instance;
    }
}

常见模式:使用对象锁

class Test{
    private static Test instance;
    private static byte[] lock = new byte[0];

    private Test(){}

    public static Test getInstance(){
        if(null==instance)
            synchronized(lock){
                if(null==instance)
                    instance = new Test();
            }
        return instance;
    }
}

常见模式:ReentranLock

class Test{
    private static Test instance;
    private static ReentranLock lock = new ReentranLock();

    private Test(){}

    public static Test getInstance(){
        if(null==instance){
            lock.lock();
            if(null==instance)
                instance = new Test();
            lock.unlock();
        }
        return instance;
    }
}

内部类

class Test{

    private Test(){}

    private static class Instance{
        public  static final Test instance = new Test();
    }

    public static Test getInstance(){
        return Instance.instance;
    }
}

你可能感兴趣的:(java,读书笔记)