HaruKishima

Java_ConnectionPool

Oct 19th, 2021 (edited)
604
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.86 KB | None | 0 0
  1. import java.sql.Connection;
  2. import java.sql.DriverManager;
  3. import java.sql.SQLException;
  4. import java.util.ArrayList;
  5. import java.util.List;
  6.  
  7. public class ConnectionPool {
  8.     String url;
  9.     List<Connection> available;
  10.     List<Connection> busy;
  11.     private static final int MAX_CONNECTION = 10;
  12.  
  13.     private ConnectionPool(String url, List<Connection> pool){
  14.         this.url = url;
  15.         this.available = pool;
  16.         busy = new ArrayList<>();
  17.     }
  18.  
  19.     public static ConnectionPool createPool(String url, int numberOfConnection) throws SQLException {
  20.         if (numberOfConnection > MAX_CONNECTION)
  21.             return null;
  22.         List<Connection> pool = new ArrayList<>();
  23.         for (int i = 0; i < numberOfConnection; i++) {
  24.             pool.add(DriverManager.getConnection(url));
  25.         }
  26.         return new ConnectionPool(url, pool);
  27.     }
  28.  
  29.     public Connection getConnection() {
  30.         Connection connection = null;
  31.         if (!available.isEmpty()) {
  32.             connection = available.get(available.size() - 1);
  33.             available.remove(connection);
  34.             busy.add(connection);
  35.         }
  36.         return connection;
  37.     }
  38.  
  39.     public boolean releaseConnection(Connection connection) {
  40.         if (busy.contains(connection)) {
  41.             available.add(connection);
  42.             busy.remove(connection);
  43.             return true;
  44.         }
  45.         return false;
  46.     }
  47.  
  48.     public void releasePool() throws SQLException {
  49.         for(Connection connection : available) {
  50.             connection.close();
  51.         }
  52.         available.clear();
  53.         for(Connection connection : busy) {
  54.             connection.close();
  55.         }
  56.         busy.clear();
  57.     }
  58.  
  59.     public int getSize() {
  60.         return available.size() + busy.size();
  61.     }
  62.  
  63.     public int getNumberAvailable() {
  64.         return available.size();
  65.     }
  66. }
  67.  
Add Comment
Please, Sign In to add comment