【发布时间】:2011-02-19 01:14:49
【问题描述】:
需要在java中创建连接池的代码吗? 我们如何确保连接池不会返回已在使用的相同对象? 如果客户端从连接池中取出连接后关闭连接会怎样?
更新 1:
我想用简单的 Java 术语创建它,并想看看它在多线程环境中是如何工作的。我的意思是哪些方法会被同步,哪些不是。这门课也会是公共课吗?如果是,那么任何人都可以访问这个类并重新初始化连接池?
更新 2:
我有一些代码如下。但我不知道“关闭来自池的连接会将其返回到池中,它不会物理关闭连接。” 我也不明白这个“因为如果从池中借用连接但尚未返回,则它不是“可用”并且不能重新分配给池的另一个客户端。”
import java.util.*;
import java.sql.*;
class ConnectionPoolManager
{
String databaseUrl = "jdbc:mysql://localhost:3306/myDatabase";
String userName = "userName";
String password = "userPass";
Vector connectionPool = new Vector();
public ConnectionPoolManager()
{
initialize();
}
public ConnectionPoolManager(
//String databaseName,
String databaseUrl,
String userName,
String password
)
{
this.databaseUrl = databaseUrl;
this.userName = userName;
this.password = password;
initialize();
}
private void initialize()
{
//Here we can initialize all the information that we need
initializeConnectionPool();
}
private void initializeConnectionPool()
{
while(!checkIfConnectionPoolIsFull())
{
System.out.println("Connection Pool is NOT full. Proceeding with adding new connections");
//Adding new connection instance until the pool is full
connectionPool.addElement(createNewConnectionForPool());
}
System.out.println("Connection Pool is full.");
}
private synchronized boolean checkIfConnectionPoolIsFull()
{
final int MAX_POOL_SIZE = 5;
//Check if the pool size
if(connectionPool.size() < 5)
{
return false;
}
return true;
}
//Creating a connection
private Connection createNewConnectionForPool()
{
Connection connection = null;
try
{
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection(databaseUrl, userName, password);
System.out.println("Connection: "+connection);
}
catch(SQLException sqle)
{
System.err.println("SQLException: "+sqle);
return null;
}
catch(ClassNotFoundException cnfe)
{
System.err.println("ClassNotFoundException: "+cnfe);
return null;
}
return connection;
}
public synchronized Connection getConnectionFromPool()
{
Connection connection = null;
//Check if there is a connection available. There are times when all the connections in the pool may be used up
if(connectionPool.size() > 0)
{
connection = (Connection) connectionPool.firstElement();
connectionPool.removeElementAt(0);
}
//Giving away the connection from the connection pool
return connection;
}
public synchronized void returnConnectionToPool(Connection connection)
{
//Adding the connection from the client back to the connection pool
connectionPool.addElement(connection);
}
public static void main(String args[])
{
ConnectionPoolManager ConnectionPoolManager = new ConnectionPoolManager();
}
}
【问题讨论】:
-
不管下面的一些答案是什么,都写你自己的连接池。将您与周围的其他人进行比较,并在此过程中了解更多有关 JDBC 和其他内容的知识。仅仅拥有一堆成熟的产品不应该阻止你制作自己的产品。只需将它们视为要被击败的标准。去吧
标签: java connection connection-pooling