I have a database manager class that manages access do the database. It contains the connections pool and 2 DAOs. Each for a different table. Looks something like this:
public class ActivitiesDatabase {
private final ConnectionSource connectionSource;
private final Dao<JsonActivity, String> jsonActivityDao;
private final Dao<AtomActivity, String> atomActivityDao;
private ActivitiesDatabase() {
try {
connectionSource = new JdbcPooledConnectionSource(Consts.JDBC);
TableUtils.createTableIfNotExists(connectionSource, JsonActivity.class);
jsonActivityDao = DaoManager.createDao(connectionSource, JsonActivity.class);
TableUtils.createTableIfNotExists(connectionSource, AtomActivity.class);
atomActivityDao = DaoManager.createDao(connectionSource, AtomActivity.class);
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
public long insertAtom(String id, String content) throws SQLException {
long additionTime = System.currentTimeMillis();
atomActivityDao.createIfNotExists(new Activity(id, content, additionTime));
return additionTime;
}
public long insertJson(String id, String content) throws SQLException {
long additionTime = System.currentTimeMillis();
jsonActivityDao.createIfNotExists(new Activity(id, content, additionTime));
return additionTime;
}
public AtomResult getAtomEntriesBetween(long from, long to) throws SQLException {
long updated = System.currentTimeMillis();
PreparedQuery<Activity> query = atomActivityDao.queryBuilder().limit(500L).orderBy(Activity.UPDATED_FIELD, true).where().between(Activity.UPDATED_FIELD, from, to).prepare();
return new Result(atomActivityDao.query(query), updated);
}
public JsonResult getJsonEntriesBetween(long from, long to) throws SQLException {
long updated = System.currentTimeMillis();
PreparedQuery<Activity> query = jsonActivityDao.queryBuilder().limit(500L).orderBy(Activity.UPDATED_FIELD, true).where().between(Activity.UPDATED_FIELD, from, to).prepare();
return new Result(jsonActivityDao.query(query), updated);
}
}
In addition, I have two thread running using the same database manager. Each thread writes to a different table. There are also threads who read from the database. A reading thread can read from any table. I noticed in the ConnectionsSource documentation that it is not thread safe.
my question is. Should I synchronize the function that write to the database. Would the answer to my question be different if both write thread were to write to the the same table?