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

错误模式

class class Test{

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

低效模式:synchronized

class class Test{

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

常见模式:使用对象锁

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

本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!

HiveServer遇到一个问题 上一篇
Java安全集合类 下一篇