I’m using a c3p0 ComboPooledDataSource with Spring and Hibernate and the solution I came up with is a custom Datasource class that accepts the actual Datasource in it’s constructor. I delegate all the responsibility to the actual datasource. I have a locked boolean which when set to true makes getConnection() wait until locked is false again.
I was just wondering whether anyone can see flaws in my approach or have better alternatives? Thanks!
public interface LockableDataSource extends DataSource {
public boolean isLocked();
public void setLocked(boolean locked);
}
public class LockableDataSourceImpl implements LockableDataSource{
private DataSource dataSource;
private boolean locked = false;
public LockableDataSourceImpl(DataSource dataSource) {
this.dataSource = dataSource;
}
public Connection getConnection() throws SQLException {
while(locked){
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
return dataSource.getConnection();
}
public Connection getConnection(String s, String s1) throws SQLException {
while(locked){
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
return dataSource.getConnection(s, s1);
}
public PrintWriter getLogWriter() throws SQLException {
return dataSource.getLogWriter();
}
public void setLogWriter(PrintWriter printWriter) throws SQLException {
dataSource.setLogWriter(printWriter);
}
public void setLoginTimeout(int i) throws SQLException {
dataSource.setLoginTimeout(i);
}
public int getLoginTimeout() throws SQLException {
return dataSource.getLoginTimeout();
}
public <T> T unwrap(Class<T> tClass) throws SQLException {
return dataSource.unwrap(tClass);
}
public boolean isWrapperFor(Class<?> aClass) throws SQLException {
return dataSource.isWrapperFor(aClass);
}
public boolean isLocked() {
return locked;
}
synchronized public void setLocked(boolean locked) {
this.locked = locked;
}
}
Several flaws:
nullonInterruptedException, which will cause hard-to-diagnose exceptions in the calling code.By far the best solution is to just shut down your app when mucking with the database.
If you really want to leave your application hung while the database is down, look at Semaphore.