Skip to content

Instantly share code, notes, and snippets.

@DarkSeraphim
Created August 26, 2014 15:21
Show Gist options
  • Save DarkSeraphim/e087eb3d5d731ea54762 to your computer and use it in GitHub Desktop.
Save DarkSeraphim/e087eb3d5d731ea54762 to your computer and use it in GitHub Desktop.
Cached PreparedStatements in connection pools. Will this work out?
public class CachedConnection implements Connection
{
// Yay for delegation :3
// Just for the non Lombok people, it will automatically
// create methods that delegate functionality to this object
@Delegate(types = Connection.class)
private final Connection connection;
private final Map<String, PreparedStatement> cachedStatements;
public CachedConnection(Connection connection)
{
this.connection = connection;
this.cachedStatements = new MapMaker().weakValues().<String, PreparedStatement>make();
}
public void query(String query, Object[] args)
{
PreparedStatement stmt = getOrPrepare(query);
// do rest
}
private PreparedStatement getOrPrepare(String query)
{
PreparedStatement stmt = this.cachedStatements.get(query);
if(stmt == null)
{
stmt = this.connection.prepareStatement(query);
this.cachedStatements.put(query, stmt);
}
return stmt;
}
protected void cleanup()
{
this.connection = null;
this.cachedStatements.clear();
this.cachedStatements = null;
}
}
public interface ConnectionPool
{
/**
* Returns a Connection if:
* - There is a valid idle connection.
* - The sum of connections is less than the max limit
* and it is able to create one.
* @return a {@link CachedConnection} from the ConnectionPool
*/
public CachedConnection lease();
/**
* Used to return a connection to the ConnectionPool,
* marking it as idle. Will call CachedConnection#cleanup().
*/
public void returnConnection(CachedConnection con);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment