这是连接池的一个非常幼稚的实现。请注意,这是使用记事本编写的,尚未经过测试:
public interface ConnectionPool {
public Connection getConnection() throws SQLException;
public void closeConnection(Connection connection) throws SQLException;
}
public class MySQLConnectionPool implements ConnectionPool {
private static final Class<?> mysqlDriver;
private final Stack<Connection> connections;
private final String url;
private final String user;
private final String password;
private final int maxSize;
static {
mysqlDriver = Class.forName("com.mysql.jdbc.Driver");
}
public MySQLConnectionPool(String url, String user, String password, int initialSize, int size) {
if (initialSize > size) {
throw new IllegalArgumentException("Pool initial size must not be greater than size");
}
if (size <= 0) {
throw new IllegalArgumentException("Pool size must be greater than zero");
}
this.size = maxSize;
this.url = url;
this.user = user;
this.password = password;
this.connections = new Stack<Connection>();
try {
for (int i = 0;i < initialSize;i++) {
connections.push(getConnection(url, user, password));
}
} catch (Exception exception) {
// TODO: Log somewhere?
}
}
public Connection getConnection(String url, user, password) throws SQLException {
DriverManager.getConnection(url, user, password);
}
public Connection getConnection() SQLException {
try {
synchronized (connections) {
return connections.pop();
}
} catch (EmptyStackException exception) {
return getConnection(url, user, password);
}
}
public void closeConnection(Connection connection) throws SQLException {
synchronized (connections) {
if (connections.size() < maxSize) {
connections.push(connection);
return;
}
}
connection.close();
}
}
public class SingletonMYSQLConnectionPool extends MySQLConnectionPool() {
private static volatile SingletonMYSQLConnectionPool instance;
private SingletonMYSQLConnectionPool() {
super("jdbc:mysql://localhost:3306/kamal","root","root", 0, 2);
}
public static SingletonMYSQLConnectionPool getInstance() {
if (instance == null) {
synchronized (SingletonMYSQLConnectionPool.class) {
if (instance == null) {
instance = new SingletonMYSQLConnectionPool();
}
}
}
return instance;
}
}