Java设计模式——单例模式——全局唯一 节省资源

场景

单例模式一个经典的应用场景就是数据库连接池的设计了。

因为频繁的建立/关闭数据库连接是比较消耗资源和时间的,所以可以设计一个池子,将使用完毕的空闲连接放入池中,等下次需要操作数据库时不用再次建立连接,直接从池中取出。

这个数据库连接池在整个程序运行期间只有一个实例,负责管理所有的数据库连接,实际上就是个单例。

单例模式,就是保证这个东西在一个周期(比如web服务器从启动到关闭的周期)只有一个具体实例的设计方法。

简单实现

package org.demo.singleton;

/**
 * Mysql数据库连接池
 */
public class MysqlPool {
	/**
	 * 保存单例的静态变量
	 */
	private static MysqlPool instance = null;
	/**
	 * 使用private修饰构造函数,防止使用new方法产生实例,保证只能从getInstance生产实例
	 */
	private MysqlPool() {
		// 此处可以一次性建立10个数据库连接,然后放到数组/list里面
		System.out.println("此处弄了1个连接池");
	}
	/**
	 * 通过该方法获取单例
	 */
	public static MysqlPool getInstance() {
		if (instance == null) {
			instance = new MysqlPool();
		}
		return instance;
	}
	/**
	 * 测试入口
	 */
	public static void main(String[] args) {
		MysqlPool pool1 = MysqlPool.getInstance();
		MysqlPool pool2 = MysqlPool.getInstance();
		System.out.println(pool1);
		System.out.println(pool2);
	}
}

运行结果如下,可见MysqlPool构造函数只运行了一次,仅生成了一个实例,下面打印pool1和pool2地址一样,也说明了pool1和pool2是一个对象。

此处弄了1个连接池
org.demo.singleton.MysqlPool@15db9742
org.demo.singleton.MysqlPool@15db9742

简单实现的bug

看起来好像很合理,一个静态变量如果是null就创建,不是null直接获取,能保证只有一个实例。

实际上是有问题的,我们写下面的代码来让它出事:

package org.demo.singleton;
/**
 * 用于测试单例的线程
 */
public class SingletonTestThread extends Thread {
	@Override
	public void run() {
		MysqlPool pool=null;
		pool=MysqlPool.getInstance();
	}
	/**
	 * 测试入口
	 */
	public static void main(String[] args) {
		for(int i=0;i<100;i++) {
			Thread thread1 = new SingletonTestThread();
			thread1.start();
		}
	}
}

运行结果如下,可见生成了不止1个MysqlPool实例。

此处弄了1个连接池
此处弄了1个连接池
此处弄了1个连接池
此处弄了1个连接池
此处弄了1个连接池
此处弄了1个连接池
此处弄了1个连接池
此处弄了1个连接池

哈哈,问题很简单,因为是多线程,所以在很短的一个时间内就有好几个线程执行了pool=MysqlPool.getInstance();,然后有好几个线程在做if (instance == null),然后有8个线程在执行if (instance == null)时instance为null,也就是说多线程下并发代码运行的速度太快了,还没等到instance = new MysqlPool();执行完,一些其他的线程就进入if (instance == null) {}体内,导致最终实际上可不止生成了一个单例。

多线程环境保持单例

之所以会出现问题,是因为多个线程在抢夺一个静态资源的时候,不讲规矩,不排队,乱来。

Java提供了synchronized关键字来保证一个方法同一个时刻只能有一个线程进入其中(synchronized功能比较复杂,此处不再深究),所以修改下再测试:

	/**
	 * 通过该方法获取单例,注意通过添加synchronized实现排他机制,同一时刻一个线程进入
	 */
	public static synchronized MysqlPool getInstance() {
		if (instance == null) {
			instance = new MysqlPool();
		}
		return instance;
	}

测试结果:

此处弄了1个连接池

效率不咋地

OK,是不是觉得很好很强大了,非也非也,要知道世界上的事情都不完美,现在是排队了,可是效率呢。

简单的添加时间检测模块,同时把getInstance执行时间加长,我们来测下:

public class MysqlPool {
	/**
	 * 保存单例的静态变量
	 */
	private static MysqlPool instance = null;
	/**
	 * 使用private修饰构造函数,防止使用new方法产生实例,保证只能从getInstance生产实例
	 */
	private MysqlPool(){
		//此处可以一次性建立10个数据库连接,然后放到数组/list里面
	}
	/**
	 * 通过该方法获取单例
	 */
	public static synchronized MysqlPool getInstance() {//此处测试时分别有synchronized和无synchronized 
		try {//模拟耗时操作
			Thread.sleep(50);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		if (instance == null) {
			instance = new MysqlPool();
		}
		return instance;
	}
	/**
	 * 测试入口
	 */
	public static void main(String[] args) {
		MysqlPool pool=null;
		for(int i=0;i<100000;i++) {
			pool=MysqlPool.getInstance();
		}
	}
}
/**
 * 用于测试单例的线程
 */
public class SingletonTestThread extends Thread {
	private static long start = 0;

	@Override
	public void run() {
		MysqlPool pool = null;
		pool = MysqlPool.getInstance();
		System.out.println(System.currentTimeMillis() - start);
	}

	/**
	 * 测试入口
	 */
	public static void main(String[] args) {
		start = System.currentTimeMillis();
		for (int i = 0; i < 100; i++) {
			Thread thread1 = new SingletonTestThread();
			thread1.start();

		}
	}
}

在没有加synchronized下测试3次,执行时间(最后一个线程结束时间减去开始时间):

58、59、59

加上synchronized测试3次:

5025、5026、5024

是不是瞬间觉得很恐怖了,确实效率太低了,就好比本来吃饭排队58秒现在5000秒,一个多小时啊,客户早就跑光了。

看来这样也不行啊。

提高多线程下效率

上面已经解决了多线程下安全问题,但是程序运行速度也大大拖慢了,主要是getInstance方法在获取单例的时候存在耗时操作,导致很多线程堵在那里。

在真实的情况下,可能耗时操作这块业务是并不需要保证加锁的,而且有时候是不需要执行耗时操作的,我们将程序修改如下:

/**
 * Mysql数据库连接池
 */
public class MysqlPool {
	/**
	 * 保存单例的静态变量
	 */
	private static MysqlPool instance = null;

	/**
	 * 使用private修饰构造函数,防止使用new方法产生实例,保证只能从getInstance生产实例
	 */
	private MysqlPool() {
		// 此处可以一次性建立10个数据库连接,然后放到数组/list里面

	}
	/**
	 * 通过该方法获取单例
	 */
	public static MysqlPool getInstance() {// 此处测试时分别有synchronized和无synchronized
		if (instance == null) {//规避不必要的耗时操作	
			try {
				// 模拟耗时操作
				Thread.sleep(50);
			} catch (Exception ex) {

			}
			synchronized(MysqlPool.class) {//仅对必须要保护的代码加锁
				if (instance == null) {	
					instance = new MysqlPool();
				}
			}
		}
		return instance;
	}
}

对上面的代码进行速度测试,发现时间回归正常水平。

/**
 * 用于测试单例的线程
 */
public class SingletonTestThread extends Thread {
	private static long start = 0;
	@Override
	public void run() {
		MysqlPool pool = null;
		pool = MysqlPool.getInstance();
		System.out.println(System.currentTimeMillis() - start);
	}
	/**
	 * 测试入口
	 */
	public static void main(String[] args) {
		start = System.currentTimeMillis();
		for (int i = 0; i < 100; i++) {
			Thread thread1 = new SingletonTestThread();
			thread1.start();
		}
	}
}

可见实际上具体问题是要具体分析的,灵活的运用synchronized加锁才能取得安全和效率上的平衡。

发布了326 篇原创文章 · 获赞 238 · 访问量 52万+

猜你喜欢

转载自blog.csdn.net/woshisangsang/article/details/81331015