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

标签 java spring hibernate

我将 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/

相关文章:

java - 如何使用Hibernate批处理

java - Spring Hibernate ehcache 设置

java - 无法在 Eclipse 中创建新的 GWT 项目

java - 查询 eureka 而不注册为服务

java - 如何在spring jpa中使用to转换器

java - hibernate 状态下有类似 Nor 的东西吗?

java - Sqlite插入和更新其他列的值

java - 如何从 Android 中的 Web 服务检索二进制数据?

java - 使用ANTLR进行多重解析

java - Spring 非法状态异常 : A JTA EntityManager cannot use getTransaction()