com.github.gkutiel.store.ConnectionPool Maven / Gradle / Ivy
package com.github.gkutiel.store;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
public class ConnectionPool {
class Connection implements AutoCloseable {
private final java.sql.Connection con;
public Connection(final java.sql.Connection con) {
this.con = con;
}
@Override
public void close() {
synchronized (cons) {
cons.add(this);
}
}
public java.sql.Statement createStatement() {
try {
return con.createStatement();
} catch (final SQLException e) {
throw new RuntimeException(e);
}
}
public PreparedStatement prepareStatement(final String sql) {
try {
return con.prepareStatement(sql);
} catch (final SQLException e) {
throw new RuntimeException(e);
}
}
}
private final String url;
private final List cons = new ArrayList<>();
public ConnectionPool(final String url) {
this.url = url;
}
public Connection get() {
try {
if (cons.isEmpty()) return new Connection(DriverManager.getConnection(url));
synchronized (cons) {
return cons.remove(0);
}
} catch (final SQLException e) {
throw new RuntimeException(e);
}
}
}