<p>In a multi-threaded application I'm working on, we occasionally see <code>ConcurrentModificationExceptions</code> on our Lists (which are mostly <code>ArrayList</code>, sometimes Vectors).  But there are other times when I think concurrent modifications are happening because iterating through the collection appears to be missing items, but no exceptions are thrown.  I know that the docs for <code>ConcurrentModificationException</code> says you can't rely on it, but how would I go about making sure I'm not concurrently modifying a List?  And is wrapping every access to the collection in a synchronized block the only way to prevent it?</p>

<p><strong>Update:</strong> Yes, I know about <code>Collections.synchronizedCollection</code>, but it doesn't guard against somebody modifying the collection while you're iterating through it.  I think at least some of my problem is happening when somebody adds something to a collection while I'm iterating through it.</p>

<p><strong>Second Update</strong>  If somebody wants to combine the mention of the synchronizedCollection and cloning like Jason did with a mention of the java.util.concurrent and the apache collections frameworks like jacekfoo and Javamann did, I can accept an answer.</p>

[{'answer_id': 75041, 'author': 'Tim Howland', 'author_id': 4276, 'author_profile': 'https://Stackoverflow.com/users/4276', 'pm_score': 2, 'selected': False, 'text': '<p>Check out <a href="http://www.javadoconline.com/search.jsp?from=main&amp;class=java.util.concurrent&amp;action=search" rel="nofollow noreferrer">java.util.concurrent</a> for versions of the standard Collections classes that are engineered to handle concurrency better.</p>\n'}, {'answer_id': 75043, 'author': 'Hank Gay', 'author_id': 4203, 'author_profile': 'https://Stackoverflow.com/users/4203', 'pm_score': 1, 'selected': False, 'text': "<p>You could try using defensive copying so that modifications to one <code>List</code> don't affect others.</p>\n"}, {'answer_id': 75048, 'author': 'Jason Cohen', 'author_id': 4926, 'author_profile': 'https://Stackoverflow.com/users/4926', 'pm_score': 2, 'selected': False, 'text': '<p>Yes you have to synchronize access to collections objects.</p>\n\n<p>Alternatively, you can use the synchronized wrappers around any existing object.  See <a href="http://java.sun.com/javase/6/docs/api/java/util/Collections.html#synchronizedList(java.util.List)" rel="nofollow noreferrer">Collections.synchronizedCollection()</a>. For example:</p>\n\n<pre><code>List&lt;String&gt; safeList = Collections.synchronizedList( originalList );\n</code></pre>\n\n<p>However all code needs to use the safe version, and even so iterating while another thread modifies will result in problems.</p>\n\n<p>To solve the iteration problem, copy the list first.  Example:</p>\n\n<pre><code>for ( String el : safeList.clone() )\n{ ... }\n</code></pre>\n\n<p>For more optimized, thread-safe collections, also look at <a href="http://www.javadoconline.com/search.jsp?from=main&amp;class=java.util.concurrent&amp;action=search" rel="nofollow noreferrer">java.util.concurrent</a>.</p>\n'}, {'answer_id': 75053, 'author': 'sblundy', 'author_id': 4893, 'author_profile': 'https://Stackoverflow.com/users/4893', 'pm_score': -1, 'selected': False, 'text': '<p><a href="http://java.sun.com/javase/6/docs/api/java/util/Collections.html#synchronizedList(java.util.List)" rel="nofollow noreferrer">Collections.synchronizedList()</a> will render a list nominally thread-safe and java.util.concurrent has more powerful features.</p>\n'}, {'answer_id': 75068, 'author': 'Mat Mannion', 'author_id': 6282, 'author_profile': 'https://Stackoverflow.com/users/6282', 'pm_score': 2, 'selected': False, 'text': "<p>Usually you get a ConcurrentModificationException if you're trying to remove an element from a list whilst it's being iterated through.</p>\n\n<p>The easiest way to test this is:</p>\n\n<pre><code>List&lt;Blah&gt; list = new ArrayList&lt;Blah&gt;();\nfor (Blah blah : list) {\n     list.remove(blah); // will throw the exception\n}\n</code></pre>\n\n<p>I'm not sure how you'd get around it. You may have to implement your own thread-safe list, or you could create copies of the original list for writing and have a synchronized class that writes to the list.</p>\n"}, {'answer_id': 75088, 'author': 'toluju', 'author_id': 12457, 'author_profile': 'https://Stackoverflow.com/users/12457', 'pm_score': 1, 'selected': False, 'text': '<p>Wrapping accesses to the collection in a synchronized block is the correct way to do this. Standard programming practice dictates the use of some sort of locking mechanism (semaphore, mutex, etc) when dealing with state that is shared across multiple threads.</p>\n\n<p>Depending on your use case however you can usually make some optimizations to only lock in certain cases. For example, if you have a collection that is frequently read but rarely written, then you can allow concurrent reads but enforce a lock whenever a write is in progress. Concurrent reads only cause conflicts if the collection is in the process of being modified.</p>\n'}, {'answer_id': 75093, 'author': 'Todd Gamblin', 'author_id': 9122, 'author_profile': 'https://Stackoverflow.com/users/9122', 'pm_score': 1, 'selected': False, 'text': "<p>ConcurrentModificationException is best-effort because what you're asking is a hard problem.   There's no good way to do this reliably without sacrificing performance besides proving that your access patterns do not concurrently modify the list.</p>\n\n<p>Synchronization would likely prevent concurrent modifications, and it may be what you resort to in the end, but it can end up being costly.  The best thing to do is probably to sit down and think for a while about your algorithm.  If you can't come up with a lock-free solution, then resort to synchronization.</p>\n"}, {'answer_id': 75196, 'author': 'Javamann', 'author_id': 10166, 'author_profile': 'https://Stackoverflow.com/users/10166', 'pm_score': 3, 'selected': False, 'text': '<p>Depending on your update frequency one of my favorites is the CopyOnWriteArrayList or CopyOnWriteArraySet. They create a new list/set on updates to avoid concurrent modification exception. </p>\n'}, {'answer_id': 75205, 'author': 'jb.', 'author_id': 7918, 'author_profile': 'https://Stackoverflow.com/users/7918', 'pm_score': 1, 'selected': False, 'text': "<p>See the implementation. It basically stores an int:</p>\n\n<pre><code>transient volatile int modCount;\n</code></pre>\n\n<p>and that is incremented when there is a 'structural modification' (like remove). If iterator detects that modCount changed it throws Concurrent modification exception. </p>\n\n<p>Synchronizing (via Collections.synchronizedXXX) won't do good since it does not guarantee iterator safety it only synchronizes writes and reads via put, get, set ...</p>\n\n<p>See java.util.concurennt and apache collections framework (it has some classes that are optimized do work correctly in concurrent environment when there is more reads (that are unsynchronized) than writes - see FastHashMap. </p>\n"}, {'answer_id': 76998, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': -1, 'selected': False, 'text': "<p>This will get rid of your concurrent modification exception. I won't speak to the efficiency however ;)</p>\n\n<pre><code>List&lt;Blah&gt; list = fillMyList();\nList&lt;Blah&gt; temp = new ArrayList&lt;Blah&gt;();\nfor (Blah blah : list) {\n     //list.remove(blah);  would throw the exception\n     temp.add(blah);\n}\nlist.removeAll(temp);\n</code></pre>\n"}, {'answer_id': 82025, 'author': 'Bill Michell', 'author_id': 7938, 'author_profile': 'https://Stackoverflow.com/users/7938', 'pm_score': 3, 'selected': True, 'text': '<p>Your original question seems to be asking for an iterator that sees live updates to the underlying collection while remaining thread-safe. This is an incredibly expensive problem to solve in the general case, which is why none of the standard collection classes do it.</p>\n\n<p>There are lots of ways of achieving partial solutions to the problem, and in your application, one of those may be sufficient.</p>\n\n<p>Jason gives <a href="https://stackoverflow.com/questions/75014/detecting-concurrent-modifications#75048">a specific way to achieve thread safety, and to avoid throwing a ConcurrentModificationException</a>, but only at the expense of liveness.</p>\n\n<p>Javamann mentions <a href="https://stackoverflow.com/questions/75014/detecting-concurrent-modifications#75196">two specific classes</a> in the <code>java.util.concurrent</code> package that solve the same problem in a lock-free way, where scalability is critical. These only shipped with Java 5, but there have been various projects that backport the functionality of the package into earlier Java versions, including <a href="http://backport-jsr166.sourceforge.net/" rel="nofollow noreferrer">this one</a>, though they won\'t have such good performance in earlier JREs.</p>\n\n<p>If you are already using some of the Apache Commons libraries, then as jacekfoo <a href="https://stackoverflow.com/questions/75014/detecting-concurrent-modifications#75205">points out</a>, the <a href="http://commons.apache.org/collections/" rel="nofollow noreferrer">apache collections framework</a> contains some helpful classes.</p>\n\n<p>You might also consider looking at the <a href="http://www.devx.com/Java/Article/36183" rel="nofollow noreferrer">Google collections framework</a>.</p>\n'}, {'answer_id': 796493, 'author': 'Sean Turner', 'author_id': 96894, 'author_profile': 'https://Stackoverflow.com/users/96894', 'pm_score': 1, 'selected': False, 'text': "<p>You can also synchronize over iteratins over the list. </p>\n\n<pre><code>List&lt;String&gt; safeList = Collections.synchronizedList( originalList );\n\npublic void doSomething() {\n   synchronized(safeList){\n     for(String s : safeList){\n           System.out.println(s);\n\n     }\n   }\n\n}\n</code></pre>\n\n<p>This will lock the list on synchronization and block all threads that try to access the list while you edit it or iterate over it. The downside is that you create a bottleneck.</p>\n\n<p>This saves some memory over the .clone() method and might be faster depending on what you're doing in the iteration... </p>\n"}]
['https://Stackoverflow.com/questions/75014', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3333/']