-
Notifications
You must be signed in to change notification settings - Fork 0
/
ConnectionPool.java
61 lines (52 loc) · 1.72 KB
/
ConnectionPool.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
package calendar.data.connection;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
public class ConnectionPool {
private static final String JDBC_URL = "jdbc:postgresql://127.0.0.1:5432/lee";
private static final String USERNAME = "lee";
private static final String PASSOWRD = "lee";
private static final int MAX_POOL_SIZE = 10;
private final List<Connection> connectionPool;
public ConnectionPool() {
connectionPool = new ArrayList<>(MAX_POOL_SIZE);
initializePool();
}
private void initializePool() {
try {
for (int i=0; i<MAX_POOL_SIZE; i++) {
Connection conn = DriverManager.getConnection(JDBC_URL, USERNAME, PASSOWRD);
conn.setAutoCommit(false);
connectionPool.add(conn);
}
} catch (SQLException e) {
e.printStackTrace();
}
}
public synchronized Connection getConnection() {
// 'synchronized' for thread safety
while (connectionPool.isEmpty()) {
try {
wait();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
return null;
}
}
return connectionPool.remove(connectionPool.size() - 1);
}
public synchronized void releaseConnection(Connection conn) {
if (conn != null) {
connectionPool.add(conn);
notify();
}
}
public synchronized void closeAllConnections() throws SQLException {
for (Connection conn: connectionPool) {
conn.close();
}
connectionPool.clear();
}
}