Skip to content

Instantly share code, notes, and snippets.

@brettwooldridge
Created August 21, 2015 14:38
Show Gist options
  • Save brettwooldridge/0137e7df79524af1c283 to your computer and use it in GitHub Desktop.
Save brettwooldridge/0137e7df79524af1c283 to your computer and use it in GitHub Desktop.
DataSource/abandoned connection killer
public class MyHikariDataSource extends HikariDataSource{
private final Timer killer = new Timer();
public Connection getConnection() throws SQLException {
final Connection c = super.getConnection();
return (Connection) Proxy.newProxyInstance(getClass().getClassLoader(), new Class[] { Connection.class }, new MyHandler(c)));
}
private class MyHandler implements InvocationHandler {
private Connection conn;
private TimerTask killerTask;
MyHandler(final Connection c) {
this.conn = c;
this.killerTask = new TimerTask() {
public void run() {
MyHikariDataSource.this.evictConnection(c);
MyHandler.this.conn = null;
MyHandler.this.killerTask = null;
}
}
}
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
if (method.getName().equals("close")) {
killerTask.cancel();
}
method.invoke(proxy, args);
}
}
}
@brettwooldridge
Copy link
Author

Oops, I missed adding the killerTask to the killer Timer with some execution delay (deadline).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment