Advertisement
Guest User

Untitled

a guest
Jun 3rd, 2017
77
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.67 KB | None | 0 0
  1. package com.atypon.registration.helper;
  2.  
  3. import java.sql.Connection;
  4. import java.sql.DriverManager;
  5. import java.util.ArrayList;
  6.  
  7. /**
  8. * This class will help us to reuse connections rather than create new one each time a connection is requested
  9. *
  10. * @author Ibrahim Al-Bzour
  11. * @version 1.0
  12. */
  13.  
  14. public class ConnectionPool {
  15.  
  16. // make ConnectionPool class as singleton because we need only one object of type ConnectionPool
  17. private static ConnectionPool instance = new ConnectionPool();
  18. private final int MAX_POOL_SIZE = 20;
  19. private String driverName, url, username, password;
  20. private ArrayList<Connection> connectionPool = new ArrayList<>();
  21. private boolean isWaiting = false;
  22.  
  23. private ConnectionPool() {
  24. this.url = Constants.DB_URL;
  25. this.username = Constants.DB_USERNAME;
  26. this.password = Constants.DB_PASSWORD;
  27. this.driverName = Constants.DB_DRIVER;
  28.  
  29. while (!checkIfConnectionPoolIsFull()) {
  30. //Adding new connection instance until the pool is full
  31. Connection connection = createNewConnectionForPool();
  32. if (connection != null)
  33. connectionPool.add(createNewConnectionForPool());
  34. else
  35. break;
  36. }
  37. }
  38.  
  39. public static ConnectionPool getInstance() {
  40. return instance;
  41. }
  42.  
  43. private boolean checkIfConnectionPoolIsFull() {
  44. // Check if the pool is full
  45. return connectionPool.size() > MAX_POOL_SIZE;
  46. }
  47.  
  48. // Creating a connection
  49. private Connection createNewConnectionForPool() {
  50. Connection connection;
  51. try {
  52. Class.forName(driverName);
  53. connection = DriverManager.getConnection(url, username, password);
  54. } catch (Exception e) {
  55. e.printStackTrace();
  56. return null;
  57. }
  58. return connection;
  59. }
  60.  
  61. public Connection getConnectionFromPool() throws InterruptedException {
  62. Connection connection = null;
  63. synchronized (this) {
  64. if (connectionPool.isEmpty()) {
  65. isWaiting = true;
  66. wait();
  67. }
  68. connection = connectionPool.get(0);
  69. connectionPool.remove(0);
  70.  
  71. }
  72. //Giving away the connection from the connection pool
  73. return connection;
  74. }
  75.  
  76. public void returnConnectionToPool(Connection connection) {
  77. //Adding the connection from the client back to the connection pool
  78. synchronized (this) {
  79. connectionPool.add(connection);
  80. if (isWaiting) {
  81. notify();
  82. isWaiting = false;
  83. }
  84. }
  85. }
  86. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement