简体   繁体   中英

Avoiding ConcurrentModificationException when serializing to Json?

We have a class Document which uses a private member of type Map<String, Object> as storage. Objects of this type are kept in memory and are (very frequently) modified by (potentially) multiple threads. It also happens that these objects (or, specifically the underlying Maps) are serialized out over HTTP on request. The serialization format is Json, and the library in use is currently Google's Gson

When serialization occurs simultaneously as a modification that introduces a new Map.Entry we see ConcurrentModificationExceptions . This makes a lot of sense intuitively, since Gson is probably iterating over the entrySet which is being modified.

How can we avoid this? Do we need to resort to always passing a deep copy of the Map to Gson? In that case, how would you implement said deep copy, given that the map can contain all Json primitives, including List and Map ?

虽然我质疑序列化一个经常更新的对象是否明智,但使用ConcurrentHashMap至少应该可以缓解并发问题。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM