I am restoring a database and I need to block any activity from it from my Java application when I do this

I am using c3p0 ComboPooledDataSource with Spring and Hibernate, and the solution I came up with is a native Datasource class that accepts the actual data source in it. I delegate all responsibility for the actual data source. I have a locked boolean which, when set to true, does getConnection () until it is locked again false.

I'm just wondering if you can see the 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; } } 
+4
source share
2 answers

A few disadvantages:

  • You do not synchronize access to the variable of your flag, so you have no guarantee that other threads will see their state.
  • You return null on InterruptedException , which will lead to a hard diagnosis of exceptions in the calling code.
  • You reimplement synchronization primitives that already exist.

Today, the best solution is to simply close the application when you are deleted from the database.

If you really want your application to freeze while the database is down, check out Semaphore .

+2
source

I would have two problems.

  • Current code is not thread safe.
  • Most non-trivial systems require multiple instances of the application. Your lock will not prevent other instances from acting in the database.
+1
source

Source: https://habr.com/ru/post/1442058/


All Articles