I have a swing application that uses some datas coming from an external mysql database.
I want these datas to be up to date, so i have a thread that check each 10seconds if new datas are available.
here’s my code :
public void run() { maj.getIgor().open(); // open the connection to Mysql while (true) { try {
if (maj.getIgor().getConnexion().isValid(2)) {
maj.checkProduits(); // update the datas
} else {
maj.getIgor().close();
maj.getIgor().open();
System.out.println("Re-try to open connection");
}
ThreadIgor.sleep(10000);
} catch (SQLException ex) {
Logger.getLogger(ThreadMajProduits.class.getName()).log(Level.SEVERE, null, ex);
} catch (InterruptedException ex) {
try {
Thread.currentThread().interrupt();
maj.getIgor().close();
} catch (SQLException ex1) {
Logger.getLogger(ThreadMajProduits.class.getName()).log(Level.SEVERE, null, ex1);
}
break;
}
}
}
I was wondering if that’s a correct way to do what i want and if there’s no risks this thread blocks my application by trying to connect to the db?
Thanks
First off, as soon as you’re using a connection pool to get connections to your DB, you shouldn’t have a problem with your thread causing any delays to your app. If you’re not using a connection pool, you will eventually introduce pauses in your main app threads, or even race conditions, if you’re not synchronizing your threads correctly.
A thought that crossed my mind when reading your question is the following, read on if interested, ignore if I guessed wrong!
What you’re doing essentially is polling the DB for “new” data. The problem is, even if you do get newer data in one of these polls, you will not have made it any safer that the next transaction your user performs will not be based on stale data. This is a fundamental concurrency problem and no matter what “tricks” you do, you cannot get away from dealing with it inside your transactions.
If what you’re trying to accomplish is to dynamically update the data of some form your user is manipulating, the correct thing to do is to use something like a “last-update” or “version” column. Then, when your user tries to push their updates to the DB, inside your transaction, you will be checking that the “last-update” or “version” of the data your user has been editing is indeed the same with the data in the DB, thus ensuring no one else has edited the same data in the meantime.