Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.sql.Connection;
- import java.sql.DriverManager;
- import java.sql.SQLException;
- import java.util.ArrayList;
- import java.util.List;
- public class ConnectionPool {
- String url;
- List<Connection> available;
- List<Connection> busy;
- private static final int MAX_CONNECTION = 10;
- private ConnectionPool(String url, List<Connection> pool){
- this.url = url;
- this.available = pool;
- busy = new ArrayList<>();
- }
- public static ConnectionPool createPool(String url, int numberOfConnection) throws SQLException {
- if (numberOfConnection > MAX_CONNECTION)
- return null;
- List<Connection> pool = new ArrayList<>();
- for (int i = 0; i < numberOfConnection; i++) {
- pool.add(DriverManager.getConnection(url));
- }
- return new ConnectionPool(url, pool);
- }
- public Connection getConnection() {
- Connection connection = null;
- if (!available.isEmpty()) {
- connection = available.get(available.size() - 1);
- available.remove(connection);
- busy.add(connection);
- }
- return connection;
- }
- public boolean releaseConnection(Connection connection) {
- if (busy.contains(connection)) {
- available.add(connection);
- busy.remove(connection);
- return true;
- }
- return false;
- }
- public void releasePool() throws SQLException {
- for(Connection connection : available) {
- connection.close();
- }
- available.clear();
- for(Connection connection : busy) {
- connection.close();
- }
- busy.clear();
- }
- public int getSize() {
- return available.size() + busy.size();
- }
- public int getNumberAvailable() {
- return available.size();
- }
- }
Add Comment
Please, Sign In to add comment