Goldman Sachs Interview Question
Java DevelopersCountry: India
Interview Type: In-Person
First of all Connection Pool mechanism uses singleton pattern so we should not use interface otherwise will not get singleton behavior using getConnection method.
Simply ArrayList can be used for connection pooling.
public class ConnectionPool {
private static List<Connection> pool = null;
private static int available = 0;
private ConnectionPool() {}
public static Connection getConnection() {
if (pool == null) {
pool = new ArrayList<Connection>();
for (int i = 0; i < 3; i++) {
try {
pool.add(new Connection());
available++;
} catch (SQLException e) {
e.printStackTrace();
}
}
}
if (pool.size() > 0) {
available--;
return pool.remove(available);
} else {
return null;
}
}
public static void put(Connection c) {
pool.add(c);
available++;
}
}
// Java 1.7
public class ConnectionPool implements Pool
{
private ConcurrentLinkedDeque<Connection> cld = new ConcurrentLinkedDeque<Connection>();
public Connection get() {
return cld.pop();
}
public void put(Connection c) {
cld.push(c);
}
}
I will go with Queue Implementation.
- Nitin July 11, 2013