gpt4 book ai didi

java - 我正在恢复一个数据库,我需要在我的 Java 应用程序中锁定它的任何 Activity

转载 作者:搜寻专家 更新时间:2023-11-01 03:09:50 24 4
gpt4 key购买 nike

我将 c3p0 ComboPooledDataSource 与 Spring 和 Hibernate 一起使用,我提出的解决方案是一个自定义数据源类,它在其构造函数中接受实际数据源。我将所有责任委托(delegate)给实际数据源。我有一个锁定的 boolean 值,当设置为 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;
}
}

最佳答案

几个缺陷:

  1. 您不同步对标志变量的访问,因此您无法保证其他线程看到它的状态。
  2. 您在 InterruptedException 上返回 null,这将导致调用代码中出现难以诊断的异常。
  3. 您正在重新实现已经存在的同步原语。

到目前为止,最好的解决方案是在处理数据库时关闭您的应用。

如果您真的想在数据库关闭时让您的应用程序挂起,请查看 Semaphore .

关于java - 我正在恢复一个数据库,我需要在我的 Java 应用程序中锁定它的任何 Activity ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13069532/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com