我正在使用带有 Spring 和 Hibernate 的 c3p0 ComboPooledDataSource,我想出的解决方案是一个自定义 Datasource 类,它在其构造函数中接受实际的 Datasource。我将所有责任委托给实际的数据源。我有一个锁定的布尔值,当设置为 true 时,会使 getConnection() 等到再次锁定为 false。
我只是想知道是否有人可以看到我的方法中的缺陷或有更好的选择?谢谢!
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;
}
}