我正在阅读官方 GAE 事务文档,但我无法理解何时会抛出ConcurrentModificationException
异常。
请看下面的示例,我将其复制粘贴在此处:
int retries = 3;
while (true) {
Transaction txn = datastore.beginTransaction();
try {
Key boardKey = KeyFactory.createKey("MessageBoard", boardName);
Entity messageBoard = datastore.get(boardKey);
long count = (Long) messageBoard.getProperty("count");
++count;
messageBoard.setProperty("count", count);
datastore.put(messageBoard);
txn.commit();
break;
} catch (ConcurrentModificationException e) {
if (retries == 0) {
throw e;
}
// Allow retry to occur
--retries;
} finally {
if (txn.isActive()) {
txn.rollback();
}
}
}
现在,所有对数据存储区的写入(在本示例中)都在事务下完成。那么为什么会抛出“ConcurrentModificationException”呢?
如果没有包含在事务中的其他代码更新了被上述代码修改的同一实体,那么会发生吗?如果确保所有更新实体的代码始终包含在事务中,是否有保证不会收到“ConcurrentModificationException”呢?