1.模拟实现一个简易的数据库连接池。
public class MyDataSource {
private static LinkedList<Connection> pool = new LinkedList<>();
private static final int INIT_CONNECTIONS = 10;
private static final String DRIVER_NAME = "com.mysql.jdbc.Driver";
private static final String URL = "";
private static final String USER = "";
private static final String PASSWORD = "";
static {
try {
Class.forName(DRIVER_NAME);
for (int i = 0; i < INIT_CONNECTIONS; i++) {
Connection connection = DriverManager.getConnection(URL, USER, PASSWORD);
pool.addLast(connection);
}
} catch (Exception e) {
e.printStackTrace();
}
}
public Connection getConnection() {
synchronized (pool) {
while (pool.size() <= 0) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
if (!pool.isEmpty()) {
return pool.removeFirst();
}
}
return null;
}
public void releaseConnection(Connection connection) {
if (connection != null) {
synchronized (pool) {
pool.addLast(connection);
notifyAll();
}
}
}
}