I am learning Java by reading source code of other authors. This Java method handles communication with SQL database. While the code does work several things concern me. For instance the try catch
block at the end of the file used as a workaround. What is the correct way of doing it? What other problems can you spot?
public void run() {
if (running) {
return;
}
running = true;
while(null == Common.server || null == Common.database || !ConnectionsPool.isInitialized()) {
// Wait until the database is set before continuing...
try {
Thread.sleep(1000);
}
catch(Exception ex) {}
}
while(running) {
final Connections cons = ConnectionsPool.getConnections();
Connection con = null;
while(!entries.isEmpty()) {
if (null == con) {
con = cons.getConnection();
}
SQLLogEntry entry = entries.remove();
if (null != entry) {
try {
write(entry, con); //find usages
}
catch (SQLException ex) {
writeLogFile("Could not write entry to SQL", ex);
}
}
}
if (null != con) {
try {
con.commit();
}
catch (SQLException ex) {
writeLogFile("Could not commit to SQL", ex);
try {
con.rollback();
}
catch (SQLException ex1) {
}
// log
final StringWriter errorOut = new StringWriter();
ex.printStackTrace(new PrintWriter(errorOut));
EditorTransactionUtil.writeLogFile(errorOut.toString());
// for user
final String msg = "Exception: " + EditorUtil.getErrorMessage(ex.getMessage());
try {
SwingUtilities.invokeAndWait(() -> {
JOptionPane.showMessageDialog(null, msg);
});
}
catch (Throwable ex1) {
}
}
finally {
cons.returnConnection(con);
}
con = null;
}
synchronized(entries) {
try {
entries.wait(1000);
}
catch (InterruptedException ex) {
// This is a workaround to process this loop...
}
}
}
writeLogFile("SQLMsgLogger run stopping...");
}