Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java.util.ConcurrentModificationException and SharedPreference

I've found this crash in crash logs. I don't know when it is happening. Can someone give me advice what is the reason? Maybe someone has same crash.

java.util.ConcurrentModificationException
       at java.util.HashMap$HashIterator.nextEntry(HashMap.java:787)
       at java.util.HashMap$KeyIterator.next(HashMap.java:814)
       at com.android.internal.util.XmlUtils.writeSetXml(XmlUtils.java:350)
       at com.android.internal.util.XmlUtils.writeValueXml(XmlUtils.java:688)
       at com.android.internal.util.XmlUtils.writeMapXml(XmlUtils.java:295)
       at com.android.internal.util.XmlUtils.writeMapXml(XmlUtils.java:264)
       at com.android.internal.util.XmlUtils.writeMapXml(XmlUtils.java:230)
       at com.android.internal.util.XmlUtils.writeMapXml(XmlUtils.java:187)
       at android.app.SharedPreferencesImpl.writeToFile(SharedPreferencesImpl.java:597)
       at android.app.SharedPreferencesImpl.access$800(SharedPreferencesImpl.java:51)
       at android.app.SharedPreferencesImpl$2.run(SharedPreferencesImpl.java:512)
       at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
       at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
       at java.lang.Thread.run(Thread.java:818)
like image 558
vmtrue Avatar asked Sep 21 '15 22:09

vmtrue


People also ask

What is Java ConcurrentModificationException?

The ConcurrentModificationException is used to fail-fast when something being iterated on is modified. This exception occurs when an object is attempted to be modified concurrently without permission.

How do you overcome ConcurrentModificationException in Java?

How do you fix Java's ConcurrentModificationException? There are two basic approaches: Do not make any changes to a collection while an Iterator loops through it. If you can't stop the underlying collection from being modified during iteration, create a clone of the target data structure and iterate through the clone.

Does HashMap throw ConcurrentModificationException?

Since Iterator of HashMap is fail-fast it will throw ConcurrentModificationException if you try to remove entry using Map.


1 Answers

We had seen this exception when using the SharedPreferences getStringSet method. This method returns a set that should not be modified. Modifying this set while the SharedPreferences object is being serialized to flash will produce a ConcurrentModificationException.

This will also happen if you use getAll and modify the returned map.

See the documentation

like image 167
nimrodm Avatar answered Sep 30 '22 13:09

nimrodm