Skip to content

Commit ac801b4

Browse files
Alejandro Gervasiopedja4
authored andcommitted
BAEL-1818 - A Guide to Connection Pools in Java (eugenp#4735)
* Strange git issue with README.MD, wouldn't revert the file * Initial Commit * Initial Commit * Update pom.xml * Update pom.xml * Initial Commit * Update pom.xml * Update source files * Update source files * Update source files * Update source files * Update Application.java * Update pom.xml * Update HikariCPDataSourceUnitTest class * Update HikariCPDataSourceUnitTest.java * Update pom.xml * Update unit test classes * Update BasicConnectionPoolUnitTest.java * Fix indentation in DBCDDataSource class * Update DBCPDataSource.java * Update BasicConnectionPool class * Update BasicConnectionPool class * Update BasicConnectionPool.java * Update BasicConnectionPool.java * Update pom.xml * Update pom.xml * BAEL-1818 Refactored getConnection(), added shutdown(), cleaned up pom.xml * BAEL-1818 Removed getConnectionPool(), upgraded c3po version * BAEL-1818 Deleted obsolete connectionpool module * BAEL-1818 Deleted obsolete connectionpool module
1 parent 86daa85 commit ac801b4

10 files changed

Lines changed: 328 additions & 5 deletions

File tree

‎core-java/pom.xml‎

Lines changed: 31 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
2-
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
2+
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
33
<modelVersion>4.0.0</modelVersion>
44
<groupId>com.baeldung</groupId>
55
<artifactId>core-java</artifactId>
@@ -73,9 +73,10 @@
7373
<dependency>
7474
<groupId>org.assertj</groupId>
7575
<artifactId>assertj-core</artifactId>
76-
<version>${assertj.version}</version>
76+
<version>${assertj-core.version}</version>
7777
<scope>test</scope>
7878
</dependency>
79+
7980
<dependency>
8081
<groupId>commons-codec</groupId>
8182
<artifactId>commons-codec</artifactId>
@@ -146,6 +147,21 @@
146147
<artifactId>icu4j</artifactId>
147148
<version>${icu4j.version}</version>
148149
</dependency>
150+
<dependency>
151+
<groupId>org.apache.commons</groupId>
152+
<artifactId>commons-dbcp2</artifactId>
153+
<version>${commons-dbcp2.version}</version>
154+
</dependency>
155+
<dependency>
156+
<groupId>com.zaxxer</groupId>
157+
<artifactId>HikariCP</artifactId>
158+
<version>${HikariCP.version}</version>
159+
</dependency>
160+
<dependency>
161+
<groupId>com.mchange</groupId>
162+
<artifactId>c3p0</artifactId>
163+
<version>${c3p0.version}</version>
164+
</dependency>
149165
</dependencies>
150166

151167
<build>
@@ -301,7 +317,7 @@
301317
</arguments>
302318
</configuration>
303319
</plugin>
304-
320+
305321
<plugin>
306322
<groupId>org.apache.maven.plugins</groupId>
307323
<artifactId>maven-javadoc-plugin</artifactId>
@@ -348,6 +364,7 @@
348364
<plugin>
349365
<groupId>org.codehaus.mojo</groupId>
350366
<artifactId>exec-maven-plugin</artifactId>
367+
<version>${exec-maven-plugin.version}</version>
351368
<executions>
352369
<execution>
353370
<id>run-benchmarks</id>
@@ -375,6 +392,7 @@
375392
</profiles>
376393

377394
<properties>
395+
378396
<!-- marshalling -->
379397
<jackson.version>2.8.5</jackson.version>
380398
<gson.version>2.8.2</gson.version>
@@ -395,24 +413,32 @@
395413
<vavr.version>0.9.0</vavr.version>
396414

397415
<!-- testing -->
398-
<assertj.version>3.6.1</assertj.version>
416+
<assertj-core.version>3.10.0</assertj-core.version>
399417

418+
<!-- JDBC pooling frameworks -->
419+
<commons-dbcp2.version>2.4.0</commons-dbcp2.version>
420+
<HikariCP.version>3.2.0</HikariCP.version>
421+
<c3p0.version>0.9.5.2</c3p0.version>
422+
400423
<!-- maven plugins -->
401424
<maven-surefire-plugin.version>2.19.1</maven-surefire-plugin.version>
402425
<springframework.spring-web.version>4.3.4.RELEASE</springframework.spring-web.version>
403426
<springframework.boot.spring-boot-starter.version>1.5.8.RELEASE</springframework.boot.spring-boot-starter.version>
427+
404428
<javamoney.moneta.version>1.1</javamoney.moneta.version>
405429
<h2database.version>1.4.197</h2database.version>
406430
<esapi.version>2.1.0.1</esapi.version>
407431
<jmh-core.version>1.19</jmh-core.version>
432+
408433
<jmh-generator-annprocess.version>1.19</jmh-generator-annprocess.version>
409434
<maven-javadoc-plugin.version>3.0.0-M1</maven-javadoc-plugin.version>
410435
<javax.mail.version>1.5.0-b01</javax.mail.version>
411436
<maven-jar-plugin.version>3.0.2</maven-jar-plugin.version>
412437
<onejar-maven-plugin.version>1.4.4</onejar-maven-plugin.version>
413438
<maven-shade-plugin.version>3.1.1</maven-shade-plugin.version>
414439
<spring-boot-maven-plugin.version>2.0.3.RELEASE</spring-boot-maven-plugin.version>
440+
<exec-maven-plugin.version>1.6.0</exec-maven-plugin.version>
415441
<icu4j.version>61.1</icu4j.version>
416442
</properties>
417443

418-
</project>
444+
</project>
Lines changed: 87 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,87 @@
1+
package com.baeldung.connectionpool.connectionpools;
2+
3+
import java.sql.Connection;
4+
import java.sql.DriverManager;
5+
import java.sql.SQLException;
6+
import java.util.ArrayList;
7+
import java.util.List;
8+
9+
public class BasicConnectionPool implements ConnectionPool {
10+
11+
private final String url;
12+
private final String user;
13+
private final String password;
14+
private final List<Connection> connectionPool;
15+
private final List<Connection> usedConnections = new ArrayList<>();
16+
private static final int INITIAL_POOL_SIZE = 10;
17+
private final int MAX_POOL_SIZE = 20;
18+
19+
public static BasicConnectionPool create(String url, String user, String password) throws SQLException {
20+
List<Connection> pool = new ArrayList<>(INITIAL_POOL_SIZE);
21+
for (int i = 0; i < INITIAL_POOL_SIZE; i++) {
22+
pool.add(createConnection(url, user, password));
23+
}
24+
return new BasicConnectionPool(url, user, password, pool);
25+
}
26+
27+
private BasicConnectionPool(String url, String user, String password, List<Connection> connectionPool) {
28+
this.url = url;
29+
this.user = user;
30+
this.password = password;
31+
this.connectionPool = connectionPool;
32+
}
33+
34+
@Override
35+
public Connection getConnection() throws SQLException {
36+
if (connectionPool.size() == 0) {
37+
if (usedConnections.size() < MAX_POOL_SIZE) {
38+
connectionPool.add(createConnection(url, user, password));
39+
} else {
40+
throw new RuntimeException("Maximum pool size reached, no available connections!");
41+
}
42+
}
43+
44+
Connection connection = connectionPool.remove(connectionPool.size() - 1);
45+
usedConnections.add(connection);
46+
return connection;
47+
}
48+
49+
@Override
50+
public boolean releaseConnection(Connection connection) {
51+
connectionPool.add(connection);
52+
return usedConnections.remove(connection);
53+
}
54+
55+
private static Connection createConnection(String url, String user, String password) throws SQLException {
56+
return DriverManager.getConnection(url, user, password);
57+
}
58+
59+
public int getSize() {
60+
return connectionPool.size() + usedConnections.size();
61+
}
62+
63+
@Override
64+
public String getUrl() {
65+
return url;
66+
}
67+
68+
@Override
69+
public String getUser() {
70+
return user;
71+
}
72+
73+
@Override
74+
public String getPassword() {
75+
return password;
76+
}
77+
78+
public void shutdown() throws SQLException {
79+
for (Connection c : usedConnections) {
80+
this.releaseConnection(c);
81+
}
82+
for (Connection c : connectionPool) {
83+
c.close();
84+
}
85+
connectionPool.clear();
86+
}
87+
}
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
package com.baeldung.connectionpool.connectionpools;
2+
3+
import com.mchange.v2.c3p0.ComboPooledDataSource;
4+
import java.beans.PropertyVetoException;
5+
import java.sql.Connection;
6+
import java.sql.SQLException;
7+
8+
public class C3poDataSource {
9+
10+
private static final ComboPooledDataSource cpds = new ComboPooledDataSource();
11+
12+
static {
13+
try {
14+
cpds.setDriverClass("org.h2.Driver");
15+
cpds.setJdbcUrl("jdbc:h2:mem:test");
16+
cpds.setUser("user");
17+
cpds.setPassword("password");
18+
} catch (PropertyVetoException e) {
19+
e.printStackTrace();
20+
}
21+
}
22+
23+
public static Connection getConnection() throws SQLException {
24+
return cpds.getConnection();
25+
}
26+
27+
private C3poDataSource(){}
28+
}
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
package com.baeldung.connectionpool.connectionpools;
2+
3+
import java.sql.Connection;
4+
import java.sql.SQLException;
5+
import java.util.List;
6+
7+
public interface ConnectionPool {
8+
9+
Connection getConnection() throws SQLException;
10+
11+
boolean releaseConnection(Connection connection);
12+
13+
String getUrl();
14+
15+
String getUser();
16+
17+
String getPassword();
18+
}
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
package com.baeldung.connectionpool.connectionpools;
2+
3+
import java.sql.Connection;
4+
import java.sql.SQLException;
5+
import org.apache.commons.dbcp2.BasicDataSource;
6+
7+
public class DBCPDataSource {
8+
9+
private static final BasicDataSource ds = new BasicDataSource();
10+
11+
static {
12+
ds.setUrl("jdbc:h2:mem:test");
13+
ds.setUsername("user");
14+
ds.setPassword("password");
15+
ds.setMinIdle(5);
16+
ds.setMaxIdle(10);
17+
ds.setMaxOpenPreparedStatements(100);
18+
}
19+
20+
public static Connection getConnection() throws SQLException {
21+
return ds.getConnection();
22+
}
23+
24+
private DBCPDataSource(){}
25+
}
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
package com.baeldung.connectionpool.connectionpools;
2+
3+
import com.zaxxer.hikari.HikariConfig;
4+
import com.zaxxer.hikari.HikariDataSource;
5+
import java.sql.Connection;
6+
import java.sql.SQLException;
7+
8+
public class HikariCPDataSource {
9+
10+
private static final HikariConfig config = new HikariConfig();
11+
private static final HikariDataSource ds;
12+
13+
static {
14+
config.setJdbcUrl("jdbc:h2:mem:test");
15+
config.setUsername("user");
16+
config.setPassword("password");
17+
config.addDataSourceProperty("cachePrepStmts", "true");
18+
config.addDataSourceProperty("prepStmtCacheSize", "250");
19+
config.addDataSourceProperty("prepStmtCacheSqlLimit", "2048");
20+
ds = new HikariDataSource(config);
21+
}
22+
23+
public static Connection getConnection() throws SQLException {
24+
return ds.getConnection();
25+
}
26+
27+
private HikariCPDataSource(){}
28+
}
Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
package com.baeldung.connectionpool;
2+
3+
import com.baeldung.connectionpool.connectionpools.BasicConnectionPool;
4+
import com.baeldung.connectionpool.connectionpools.ConnectionPool;
5+
import java.sql.Connection;
6+
import java.sql.SQLException;
7+
import java.util.List;
8+
import static org.assertj.core.api.Assertions.assertThat;
9+
import static org.junit.Assert.assertTrue;
10+
import static org.junit.Assert.fail;
11+
12+
import org.junit.BeforeClass;
13+
import org.junit.Test;
14+
15+
public class BasicConnectionPoolUnitTest {
16+
17+
private static ConnectionPool connectionPool;
18+
19+
@BeforeClass
20+
public static void setUpBasicConnectionPoolInstance() throws SQLException {
21+
connectionPool = BasicConnectionPool.create("jdbc:h2:mem:test", "user", "password");
22+
}
23+
24+
@Test
25+
public void givenBasicConnectionPoolInstance_whenCalledgetConnection_thenCorrect() throws Exception {
26+
assertTrue(connectionPool.getConnection().isValid(1));
27+
}
28+
29+
@Test
30+
public void givenBasicConnectionPoolInstance_whenCalledreleaseConnection_thenCorrect() throws Exception {
31+
Connection connection = connectionPool.getConnection();
32+
assertThat(connectionPool.releaseConnection(connection)).isTrue();
33+
}
34+
35+
@Test
36+
public void givenBasicConnectionPoolInstance_whenCalledgetUrl_thenCorrect() {
37+
assertThat(connectionPool.getUrl()).isEqualTo("jdbc:h2:mem:test");
38+
}
39+
40+
@Test
41+
public void givenBasicConnectionPoolInstance_whenCalledgetUser_thenCorrect() {
42+
assertThat(connectionPool.getUser()).isEqualTo("user");
43+
}
44+
45+
@Test
46+
public void givenBasicConnectionPoolInstance_whenCalledgetPassword_thenCorrect() {
47+
assertThat(connectionPool.getPassword()).isEqualTo("password");
48+
}
49+
50+
@Test(expected = RuntimeException.class)
51+
public void givenBasicConnectionPoolInstance_whenAskedForMoreThanMax_thenError() throws Exception {
52+
// this test needs to be independent so it doesn't share the same connection pool as other tests
53+
ConnectionPool cp = BasicConnectionPool.create("jdbc:h2:mem:test", "user", "password");
54+
final int MAX_POOL_SIZE = 20;
55+
for (int i = 0; i < MAX_POOL_SIZE + 1; i++) {
56+
cp.getConnection();
57+
}
58+
fail();
59+
}
60+
61+
@Test
62+
public void givenBasicConnectionPoolInstance_whenSutdown_thenEmpty() throws Exception {
63+
ConnectionPool cp = BasicConnectionPool.create("jdbc:h2:mem:test", "user", "password");
64+
assertThat(((BasicConnectionPool)cp).getSize()).isEqualTo(10);
65+
66+
((BasicConnectionPool) cp).shutdown();
67+
assertThat(((BasicConnectionPool)cp).getSize()).isEqualTo(0);
68+
}
69+
}
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
package com.baeldung.connectionpool;
2+
3+
import com.baeldung.connectionpool.connectionpools.C3poDataSource;
4+
import java.sql.SQLException;
5+
import static org.junit.Assert.assertTrue;
6+
import org.junit.Test;
7+
8+
public class C3poDataSourceUnitTest {
9+
10+
@Test
11+
public void givenC3poDataSourceClass_whenCalledgetConnection_thenCorrect() throws SQLException {
12+
assertTrue(C3poDataSource.getConnection().isValid(1));
13+
}
14+
}
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
package com.baeldung.connectionpool;
2+
3+
import com.baeldung.connectionpool.connectionpools.DBCPDataSource;
4+
import java.sql.SQLException;
5+
import static org.junit.Assert.assertTrue;
6+
import org.junit.Test;
7+
8+
public class DBCPDataSourceUnitTest {
9+
10+
@Test
11+
public void givenDBCPDataSourceClass_whenCalledgetConnection_thenCorrect() throws SQLException {
12+
assertTrue(DBCPDataSource.getConnection().isValid(1));
13+
}
14+
}

0 commit comments

Comments
 (0)