ConcurrentModifcationException偶尔发生

时间:2018-10-11 11:45:05

标签: java android parse-platform

我有一个带有一行的函数,据说该行可以防止并发修改异常 列出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 个答案:

答案 0 :(得分:4)

HashMap不是线程安全的数据结构,因此可以使用ConcurrentHashMap代替HashMap

使用ConcurrentHashMap<String, ConcurrentHashMap<String, WritableMap>> topLevel 代替 HashMap<String, HashMap<String, WritableMap>> topLevel

并放入List<String> parseObjectKeys = new ArrayList<>(parseObject.keySet());synchronized块中。

希望这会有所帮助。

答案 1 :(得分:1)

解决方案!

添加这样的同步块

private synchronized void convertParseObject() { }