Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package com.atypon.registration.helper;
- import java.sql.Connection;
- import java.sql.DriverManager;
- import java.util.ArrayList;
- /**
- * This class will help us to reuse connections rather than create new one each time a connection is requested
- *
- * @author Ibrahim Al-Bzour
- * @version 1.0
- */
- public class ConnectionPool {
- // make ConnectionPool class as singleton because we need only one object of type ConnectionPool
- private static ConnectionPool instance = new ConnectionPool();
- private final int MAX_POOL_SIZE = 20;
- private String driverName, url, username, password;
- private ArrayList<Connection> connectionPool = new ArrayList<>();
- private boolean isWaiting = false;
- private ConnectionPool() {
- this.url = Constants.DB_URL;
- this.username = Constants.DB_USERNAME;
- this.password = Constants.DB_PASSWORD;
- this.driverName = Constants.DB_DRIVER;
- while (!checkIfConnectionPoolIsFull()) {
- //Adding new connection instance until the pool is full
- Connection connection = createNewConnectionForPool();
- if (connection != null)
- connectionPool.add(createNewConnectionForPool());
- else
- break;
- }
- }
- public static ConnectionPool getInstance() {
- return instance;
- }
- private boolean checkIfConnectionPoolIsFull() {
- // Check if the pool is full
- return connectionPool.size() > MAX_POOL_SIZE;
- }
- // Creating a connection
- private Connection createNewConnectionForPool() {
- Connection connection;
- try {
- Class.forName(driverName);
- connection = DriverManager.getConnection(url, username, password);
- } catch (Exception e) {
- e.printStackTrace();
- return null;
- }
- return connection;
- }
- public Connection getConnectionFromPool() throws InterruptedException {
- Connection connection = null;
- synchronized (this) {
- if (connectionPool.isEmpty()) {
- isWaiting = true;
- wait();
- }
- connection = connectionPool.get(0);
- connectionPool.remove(0);
- }
- //Giving away the connection from the connection pool
- return connection;
- }
- public void returnConnectionToPool(Connection connection) {
- //Adding the connection from the client back to the connection pool
- synchronized (this) {
- connectionPool.add(connection);
- if (isWaiting) {
- notify();
- isWaiting = false;
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement