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;
    }
}

猜你喜欢

转载自blog.csdn.net/awdac/article/details/80297246