⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 connectionpool.java

📁 一个关于商业的网站
💻 JAVA
字号:
package com.everstar.database;

import java.sql.*;
import java.util.*;
import java.util.Date;
import java.util.*;
import com.coolservlets.forum.*;
import com.coolservlets.util.*;
import java.io.*;

class ConnectionPool
{
	private int		m_nCheckedOut;
	private int		m_nMaxConn;

	private String	m_strPoolName;

	private String	m_strUser;
	private String	m_strPasswd;
	private String	m_strURL;

	private Vector	m_vectFreeConnPool = new Vector();

	public ConnectionPool(String strPoolName, String strURL, String strUser,
							String strPasswd,int nMaxConn)
	{
		this.m_strPoolName	= strPoolName;
		this.m_strURL		= strURL;
		this.m_strUser		= strUser;
		this.m_strPasswd	= strPasswd;
		this.m_nMaxConn		= nMaxConn;
	}

	public synchronized void freeConnection(Connection con)
	{
		//If a freem connection is available, add it to the end of the queue
		//I use the FIFO algorithm in the Connection Pool
		if(con == null)	return;
		m_vectFreeConnPool.addElement(con);
		m_nCheckedOut--;

		//Wakes up all threads that are waiting for this object's monitor
		notifyAll();
	}

	public synchronized Connection getConnection()
	{
		Connection con = null;

		if (m_vectFreeConnPool.size() > 0)
		{
			con = (Connection) m_vectFreeConnPool.firstElement();
			m_vectFreeConnPool.removeElementAt(0);

			try
			{
				if (con.isClosed())
				{
					// recursion
					con = getConnection();
				}
			}
			catch(SQLException e)
			{
				// recursion
				con = getConnection();
			}
		}
		else if (m_nMaxConn == 0 || m_nCheckedOut < m_nMaxConn)
		{
			con = newConnection();
		}

		if (con != null)
		{
			m_nCheckedOut++;
		}
		StringWriter sout = new StringWriter();
		return con;
	}

	public synchronized Connection getConnection(long timeout)
	{
		long dateStartTime = new Date().getTime();
		Connection con;

		while ((con = getConnection()) == null)
		{
			try
			{
				// Waiting for ...
				wait(timeout);
			}
			catch (InterruptedException e)
			{}

			if ((new Date().getTime() - dateStartTime) >= timeout)
			{
				// Overtime,return null
				return null;
			}
		}
		return con;
	}

	public synchronized void release()
	{
		Enumeration enumAllConnections = m_vectFreeConnPool.elements();
		while (enumAllConnections.hasMoreElements())
		{
			Connection con = (Connection) enumAllConnections.nextElement();
			try
			{
				con.close();	//Close the connection
			}
			catch (SQLException e)
			{
			}
		}

		//Clear the pool
		m_vectFreeConnPool.removeAllElements();
	}

	private Connection newConnection()
	{
		Connection con = null;
		try
		{
			if (m_strUser == null)
			{
				con = DriverManager.getConnection(m_strURL);
			}
			else
			{
				con = DriverManager.getConnection(m_strURL, m_strUser, m_strPasswd);
			}
		}
		catch (SQLException e)
		{
			return null;
		}

		return con;
	}
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -