Tia*_* Na 2 java database connection pool object
如果可以实现它,你能看看我的连接池吗?
public class ConnectionPool {
private static List<DBConnection> pool = null;
private static int available = 0;
private ConnectionPool() {}
public static DBConnection getConnection() {
if (pool == null) {
pool = new ArrayList<DBConnection>();
for (int i = 0; i < 3; i++) {
try {
pool.add(new DBConnection());
available++;
} catch (SQLException e) {
e.printStackTrace();
}
}
}
if (pool.size() > 0) {
available--;
return pool.remove(available);
} else {
return null;
}
}
public static void returnConnection(DBConnection c) {
pool.add(c);
available++;
}
}
Run Code Online (Sandbox Code Playgroud)
我只使用一个数组,客户端应该要求连接池使用连接,然后将其返回到连接池.
Connection connection = ConnectionPool.getConnection();
connection.execute("insert into users values('"+user.getUsername()+"', '"+user.getPassword()+"', '"+user.getGroup()+"', '"+banned+"', '"+broker+admin+sharehodler+company+"')");
ConnectionPool.returnConnection(connection);
connection = null;
Run Code Online (Sandbox Code Playgroud)
我需要有关此实施的反馈.谢谢
有一些观点使这种实现很成问题.
ConnectionPool.我确信还有更多要点,但除非这些是固定的,否则继续没有用处.
池实现的一个大问题是您将裸连接传递给池的调用者.这意味着有人可以从您的池中获取连接,关闭它,然后将其返回到池中.这很糟糕.
解决此问题的常用方法是使用委托包装返回连接对象,并使它们忽略对close方法的调用(甚至更好,使close()安全地返回到池的底层连接).
其他主要问题:
总而言之,您应该重用现有的连接池实现,而不是自己编写.目前,许多类型4的驱动程序都在驱动程序中包含自己的连接池.