出于测试目的,我将以下代码放在 Activity 的 onCreate() 中:
// Create 50 objects
for (int i = 0; i < 50; i++) {
ParseObject obj = new ParseObject("test_obj");
obj.put("foo", "bar");
try {
obj.save();
} catch (ParseException pe) {
Log.d("Parsetest", "Failed to save " + pe.toString());
}
}
// Count them
for (int i = 0; i < 10; i ++) {
ParseQuery<ParseObject> query = ParseQuery.getQuery("test_obj");
query.countInBackground(new CountCallback() {
@Override
public void done(int count, ParseException e) {
if (e == null) {
Log.d("Parsetest", "Background found " + count + " objects");
} else {
Log.d("Parsetest", "Query issue" + e.toString());
}
}
});
}
我希望计数始终为 50,但是运行此代码会产生如下结果:
D/Parsetest(17761): Background found 0 objects
D/Parsetest(17761): Background found 0 objects
D/Parsetest(17761): Background found 0 objects
D/Parsetest(17761): Background found 0 objects
D/Parsetest(17761): Background found 0 objects
D/Parsetest(17761): Background found 0 objects
D/Parsetest(17761): Background found 50 objects
D/Parsetest(17761): Background found 0 objects
D/Parsetest(17761): Background found 0 objects
D/Parsetest(17761): Background found 0 objects
有人可以解释这种行为以及如何纠正吗?
最佳答案
在不知道更多细节的情况下,我倾向于认为这种不一致是由于线程和同步/异步调用的混合造成的。
例如,调用 obj.save();
是同步的 ( reference ),但是,如果没有看到您的其余代码,同步的可能是正在后台线程上执行保存。
此外,query.countInBackground
是异步的 并使用for 循环多次调用。这将同时创建 10 个独立的后台进程来查询 Parse 的对象数量,并且根据保存的处理方式,可能会出现竞争条件。
最后,there are documented limitations使用 Parse 进行计数操作。
Count queries are rate limited to a maximum of 160 requests per minute. They can also return inaccurate results for classes with more than 1,000 objects. Thus, it is preferable to architect your application to avoid this sort of count operation (by using counters, for example.)
来自 Héctor Ramos on the Parse Developers Google group ,
Count queries have always been expensive once you throw some constraints in. If you only care about the total size of the collection, you can run a count query without any constraints and that one should be pretty fast, as getting the total number of records is a different problem than counting how many of these match an arbitrary list of constraints. This is just the reality of working with database systems.
考虑到计数操作的成本,Parse 可能有适当的机制来防止来自给定客户端的计数操作的快速爆发。
如果您需要经常执行计数操作,推荐的方法是使用云代码 afterSave Hook 根据需要递增/递减计数器。
关于java - Q : Parse. com查询计数稳定性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33347766/