我有一个函数,其中一行应该是为了防止并发修改异常 List parseObjectKeys = new ArrayList<>(parseObject.keySet()); 然而它仍然时不时地发生 private static void convertParseObject(ParseObject parseObject, HashMap<String, HashMap<String, WritableMap>> topLevel, ArrayList<Task<Void>> tasks) { if (parseObject != null) { String className = parseObject.getClassName(); String id = parseObject.getObjectId(); if (!topLevel.containsKey(className)) { topLevel.put(className, new HashMap<String, WritableMap>()); } if (!topLevel.get(className).containsKey(id)) { final WritableMap flatMap = Arguments.createMap(); flatMap.putString("class", className); flatMap.putString("id", id); if (parseObject.isDataAvailable()) { topLevel.get(className).put(id, flatMap); // This is required to prevent a ConcurrentModificationException List<String> parseObjectKeys = new ArrayList<>(parseObject.keySet()); for (final String key : parseObjectKeys) { Object value = parseObject.get(key); if (value instanceof String) { flatMap.putString(key, (String) value); } else if (value instanceof Boolean) { flatMap.putBoolean(key, (Boolean) value); } else if (value instanceof Integer) { flatMap.putInt(key, (Integer) value); } else if (value instanceof Double) { flatMap.putDouble(key, (Double) value); } else if (value instanceof Date) { flatMap.putString(key, Utils.toISO8601UTC((Date)value)); } else { if (value != null && !(value instanceof ParseACL)) { Log.e(TAG, "Unknown type: " + value.getClass()); } } } } }}
2 回答
HUWWW
TA贡献1874条经验 获得超12个赞
HashMap
不是线程安全的数据结构,因此您可以使用ConcurrentHashMap
代替HashMap
。
使用ConcurrentHashMap<String, ConcurrentHashMap<String, WritableMap>> topLevel
代替 HashMap<String, HashMap<String, WritableMap>> topLevel
.
并把List<String> parseObjectKeys = new ArrayList<>(parseObject.keySet());
在synchronized
块。
希望它会有所帮助。
添加回答
举报
0/150
提交
取消