我有一个游戏,它每隔 X 秒就会将内存中的更改值写回我的数据库。当它们保存的数据被编辑时,这些值存储在容器(HashMaps 和 ArrayLists)中。
为简单起见,假设我只有 1 个容器可以写入数据库:
public static HashMap<String, String> dbEntitiesDeletesBacklog = new HashMap<String, String>();
我的数据库写入循环:
Timer dbUpdateJob = new Timer();
dbUpdateJob.schedule(new TimerTask() {
public void run() {
long startTime = System.nanoTime();
boolean updateEntitiesTableSuccess = UpdateEntitiesTable();
if (!updateEntitiesTableSuccess){
try {
conn.rollback();
} catch (SQLException e) {
e.printStackTrace();
logger.fatal(e.getMessage());
System.exit(1);
}
} else { //everything saved to DB - commit time
try {
conn.commit();
} catch (SQLException e) {
e.printStackTrace();
logger.fatal(e.getMessage());
System.exit(1);
}
}
logger.debug("Time to save to DB: " + (System.nanoTime() - startTime) / 1000000 + " milliseconds");
}
}, 0, 10000); //TODO:: figure out the perfect saving delay
我的更新方法:
private boolean UpdateEntitiesTable() {
Iterator<Entry<String, String>> it = dbEntitiesDeletesBacklog.entrySet().iterator();
while (it.hasNext()) {
Entry<String, String> pairs = it.next();
String tmpEntityId = pairs.getKey();
int deletedSuccess = UPDATE("DELETE" +
" FROM " + DB_NAME + ".entities" +
" WHERE entity_id=(?)", new String[]{tmpEntityId});
if (deletedSuccess != 1) {
logger.error("Entity " + tmpEntityId + " was unable to be deleted.");
return false;
}
it.remove();
dbEntitiesDeletesBacklog.remove(tmpEntityId);
}
在为 dbEntitiesDeletesBacklog HashMap 和本摘录中未包含的其他容器“保存到数据库”时,我是否需要创建某种锁定机制?我认为我需要这样做,因为它创建了它的迭代器,然后循环。如果在创建迭代器之后添加一些东西,并且在它完成遍历条目之前添加一些东西怎么办。很抱歉,这更像是一个流程问题,而不是代码帮助问题(因为我包含了这么多示例代码),但我想确保很容易理解我想要做什么和问什么。
我使用的其他容器也有同样的问题:
public static ArrayList<String> dbCharacterDeletesBacklog = new ArrayList<String>();
private boolean DeleteCharactersFromDB() {
for (String deleteWho : dbCharacterDeletesBacklog){
int deleteSuccess = MyDBSyncher.UPDATE("DELETE FROM " + DB_NAME + ".characters" +
" WHERE name=(?)",
new String[]{deleteWho});
if (deleteSuccess != 1) {
logger.error("Character(deleteSuccess): " + deleteSuccess);
return false;
}
}
dbCharacterDeletesBacklog.clear();
return true;
}
非常感谢,一如既往,在这方面的任何帮助。非常感谢!