--- /dev/null
+/**
+ * Macaco
+ * Copyright (c) 2009-2015 Marco Zanon <info@marcozanon.com>.
+ * Released under MIT license (see LICENSE for details).
+ */
+
+package com.marcozanon.macaco.sql;
+
+import com.marcozanon.macaco.MObject;
+import java.util.LinkedList;
+
+public class MSqlConnectionPool extends MObject {
+
+ protected MSqlConnectionGenerator connectionGenerator = null;
+
+ protected int minimumSize = 0;
+ protected int maximumSize = 0;
+ protected LinkedList<MSqlConnection> connectionPool = new LinkedList<MSqlConnection>();
+
+ /* */
+
+ public MSqlConnectionPool(String driver, String url, String username, String password, int minimumSize, int maximumSize) throws MSqlConnectionFailureException {
+ super();
+ //
+ if (0 > minimumSize) {
+ throw new IllegalArgumentException(String.format("Invalid 'minimumSize': %s.", minimumSize));
+ }
+ if (1 > maximumSize) {
+ throw new IllegalArgumentException(String.format("Invalid 'maximumSize': %s.", maximumSize));
+ }
+ else if (minimumSize > maximumSize) {
+ throw new IllegalArgumentException(String.format("Invalid 'maximumSize': %s < %s ('minimumSize').", maximumSize, minimumSize));
+ }
+ //
+ this.connectionGenerator = new MSqlConnectionGenerator(driver, url, username, password);
+ this.minimumSize = minimumSize;
+ this.maximumSize = maximumSize;
+ //
+ this.initializeConnectionPool();
+ }
+
+ /* Connection generator */
+
+ protected MSqlConnectionGenerator getConnectionGenerator() {
+ return this.connectionGenerator;
+ }
+
+ /* Connection pool */
+
+ protected int getMinimumSize() {
+ return this.minimumSize;
+ }
+
+ protected int getMaximumSize() {
+ return this.maximumSize;
+ }
+
+ protected LinkedList<MSqlConnection> getConnectionPool() {
+ return this.connectionPool;
+ }
+
+ protected void initializeConnectionPool() throws MSqlConnectionFailureException {
+ for (int c = 0; c < this.getMinimumSize(); c++) {
+ MSqlConnection connection = this.getConnectionGenerator().getConnection();
+ this.getConnectionPool().add(connection);
+ }
+ }
+
+ public synchronized MSqlConnection popConnection() throws MSqlConnectionFailureException {
+ LinkedList<MSqlConnection> connectionPool = this.getConnectionPool();
+ MSqlConnection connection = connectionPool.removeLast();
+ if (this.getMinimumSize() > connectionPool.size()) {
+ connectionPool.add(this.getConnectionGenerator().getConnection());
+ }
+ return connection;
+ }
+
+ public synchronized void pushConnection(MSqlConnection connection) {
+ if (null == connection) {
+ throw new IllegalArgumentException("Invalid 'connection': null.");
+ }
+ //
+ LinkedList<MSqlConnection> connectionPool = this.getConnectionPool();
+ if (this.getMaximumSize() >= connectionPool.size()) {
+ connectionPool.add(connection);
+ }
+ }
+
+}