Java并发编程原理与实战二十四:简易数据库连接池

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();
}
}
}
}

参考资料:

《java并发编程实战》龙果学院

上一篇:Java并发编程原理与实战四十:JDK8新增LongAdder详解


下一篇:Java并发编程原理与实战四十四:final域的内存语义