0

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?

4

2 回答 2

1

我在 ConnectionsSource 文档中注意到它不是线程安全的。

对,但您使用的JdbcPooledConnectionSource是线程安全的。

我会同步写入数据库的函数吗?

ORMLite 这样做应该没有问题。但是,您需要确保您的数据库支持多个并发数据库更新。例如,如果您使用 MySQL、Postgres 或 Oracle,则不会有问题。您需要阅读 H2 多线程,以了解需要使用哪些选项才能使其正常工作。

如果两个写入线程都写入同一个表,我的问题的答案会有所不同吗?

那会增加并发性,所以(呃)也许?同样,它取决于数据库类型。

于 2013-12-17T23:10:22.490 回答
0

您可以将连接池用于与 ORMLite 一起工作的多线程这里是javaDoc

于 2013-10-23T12:46:29.617 回答