-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDBConnectionPool
101 lines (77 loc) · 2.4 KB
/
DBConnectionPool
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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
package DBConnectionPool;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeUnit;
public class DBConnectionPool {
private final BlockingQueue<Connection> pool;
private final String dbUrl;
private final String dbUser;
private final String dbPassword;
private int poolSize;
public DBConnectionPool(String dbUrl,String dbUser,String dbPassword,int poolSize) throws SQLException {
this.dbUrl=dbUrl;
this.dbPassword=dbPassword;
this.dbUser=dbUser;
this.poolSize=poolSize;
this.pool = new ArrayBlockingQueue<>(poolSize);
for(int i=0;i<poolSize;i++) {
pool.add(createNewConnection());
}
}
private Connection createNewConnection() throws SQLException{
return DriverManager.getConnection(dbUrl,dbUser,dbPassword);
}
public Connection borrowConnection(long timeout,TimeUnit unit) throws InterruptedException, SQLException {
Connection connection=pool.poll(timeout,unit);
if(connection==null) {
throw new SQLException("Timed out while waiting for a connection");
}
System.out.println("Connection established");
return connection;
}
public void retrunConnection(Connection connection) {
if(connection!=null) {
System.out.println("Connection returned");
pool.offer(connection);
}
}
public synchronized void shutdown() throws SQLException {
for(Connection connection:pool) {
if(connection!=null) {
connection.close();
}
}
pool.clear();
}
public static class task implements Runnable{
private final DBConnectionPool pool;
public task(DBConnectionPool pool) {
this.pool=pool;
}
@Override
public void run() {
Connection connection = null;
try {
connection = pool.borrowConnection(5, TimeUnit.SECONDS);
Thread.sleep(2000);
} catch (InterruptedException | SQLException e1) {
System.out.println(Thread.currentThread().getName()+" Failed to get DB Connection");
}finally {
if(connection!=null) {
pool.retrunConnection(connection);
}
}
}
}
public static void main(String[] args) throws SQLException, InterruptedException {
DBConnectionPool pool=new DBConnectionPool("jdbc:mysql://localhost:3306/mydb","user","password",5);
for(int i=0;i<5;i++) {
new Thread(new task(pool)).start();
}
Thread.sleep(10000);
pool.shutdown();
}
}