笔记留着查阅

public class ConnectionPool {	
	private int minConn = 5;
	private int maxConn = 10;
	private String driver = null;
	private String url = null;
	private String userName = null;
	private String passWord = null;
	private static ConnectionPool connPool = null;
	
	private int ctConn = 0;
	private Stack stack = new Stack();
	
	private ConnectionPool() {
		try {
			this.driver = StringUtils.getResResource("driver");
			this.url = StringUtils.getResResource("url");
			this.userName = StringUtils.getResResource("userName");
			this.passWord = StringUtils.getResResource("passWord");
			Class.forName(this.driver);
			for(int i = 0; i < minConn; i++) {
				this.stack.push(this.createConnection());
				this.ctConn ++;
			}
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
	}
	
	private Connection createConnection() {
		Connection conn = null;
		try {
			conn = DriverManager.getConnection(this.url, userName, passWord);
		}  catch (SQLException e) {
			e.printStackTrace();
		}
		return conn;
	}
	
	public static synchronized ConnectionPool getInstance() {
		if(connPool != null) {
			return connPool;
		} else {
			connPool = new ConnectionPool();
			return connPool;
		}
	}
	
	public synchronized Connection getConn() {
		Connection conn = null;
		if(!(this.stack.isEmpty())) {
			conn = (Connection)this.stack.pop();
		} else if(this.ctConn < this.maxConn) {
			conn = this.createConnection();
			this.ctConn ++;
		} else {
			try {
				wait(1000);
				conn = getConn();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		return conn;
	}
	
	public synchronized void releasConn(Connection conn) {
		this.stack.push(conn);
		notifyAll();
	}
	
}

你可能感兴趣的:(笔记)