I'm studying design patterns, and to demonstrate a singleton, I've implemented a primitive database connection pool.
ConnectionPool.java
package com.levent.connpool;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class ConnectionPool {
private final static int MAX_CONNECTIONS = 8;
private static ConnectionPool instance = null; // lazy loading
private static Connection[] connections = new Connection[MAX_CONNECTIONS];
private static String dbUrl = "jdbc:derby://localhost:1527/memory:levoDB/singletonDemo;create=true";
private static int counter;
private ConnectionPool() { }
public static ConnectionPool getInstance() {
if(instance == null) {
synchronized(ConnectionPool.class) {
if(instance == null) {
instance = new ConnectionPool();
initializeConnections();
counter = 0;
}
}
}
return instance;
}
private static void initializeConnections() {
for(int i = 0; i < MAX_CONNECTIONS; i++) {
try {
connections[i] = DriverManager.getConnection(dbUrl);
} catch (SQLException e) {
e.printStackTrace();
}
}
}
public static Connection getConnection() {
counter++;
if(counter == Integer.MAX_VALUE)
counter = 0;
return connections[counter%MAX_CONNECTIONS];
}
}
ConnectionPoolDemo.java
package com.levent.connpool;
import java.sql.Connection;
import java.sql.SQLException;
public class ConnectionPoolDemo {
public static void main(String[] args) {
ConnectionPool pool = ConnectionPool.getInstance();
Connection[] connections = new Connection[17];
for(int i = 0; i < connections.length; i++)
connections[i] = pool.getConnection();
int preIndex = connections[0].getClass().getCanonicalName().length();
for(int i = 0; i < connections.length; i++)
System.out.printf("Connection %2d : %s\n", i+1, connections[i].toString().substring(preIndex));
for(int i = 0; i < connections.length; i++)
try {
connections[i].close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
The output is as follows:
Connection 1 : @27f8302d Connection 2 : @6438a396 Connection 3 : @e2144e4 Connection 4 : @6477463f Connection 5 : @3d71d552 Connection 6 : @1cf4f579 Connection 7 : @18769467 Connection 8 : @46ee7fe8 Connection 9 : @27f8302d Connection 10 : @6438a396 Connection 11 : @e2144e4 Connection 12 : @6477463f Connection 13 : @3d71d552 Connection 14 : @1cf4f579 Connection 15 : @18769467 Connection 16 : @46ee7fe8 Connection 17 : @27f8302d
Explanation
The aims is to have distributed connections that's why on each getConnection()
method call, on of the each connections are returned with the use of mod. The maximum connection size is determined by the MAX_CONNECTIONS
which is set to 8 in this example and all 17 connections retrieved from the singleton pool class are recurring instances of the 8 connections stored in the ConnectionPool
class.
I know that this code is not a big shot, but my aim was to demonstrate a simple singleton in a real world example. I'm waiting for your ideas and your criticism.