-1

The following method throws a ConcurrentModificationException because the list it iterates over gets modified. Can I use synchronised to lock... something... either while the list is modified or iterated over?

How would I go about doing that? I've tried a few ways but none of them seem to work. Locking "this" doesn't work, for instance.

public class Deck extends ArrayList<Card> {
...
    public void render(Canvas canvas) {
       for (Card card : this) {
           // Do stuff
       }
    }
...
}
abc32112
  • 2,457
  • 9
  • 37
  • 53
  • 1
    possible duplicate of [Concurrent Modification exception](http://stackoverflow.com/questions/1496180/concurrent-modification-exception) – Selvin Nov 25 '14 at 16:36
  • That question doesn't have an accepted answer. The iterator solutions suggested seem to have the same problem, that the iterator cannot handle concurrent modification. – abc32112 Nov 25 '14 at 16:51
  • Possible duplicate of [ConcurrentModificationException despite using synchronized](http://stackoverflow.com/questions/1655362/concurrentmodificationexception-despite-using-synchronized) – Raedwald Jan 22 '16 at 16:00

1 Answers1

0

You need to use an iterator and it's methods to add/remove items, for example:

public class Deck extends ArrayList<Card> {
...
    public void render(Canvas canvas) {

       Iterator<Card> it = iterator();
       while (it.hasNext()) {
           Card card = it.next;
           // Do stuff
           // remove card
           it.remove();
           // add new card
           it.add(new Card());
       }
    }
...
}
Flexo
  • 87,323
  • 22
  • 191
  • 272
andrei
  • 2,934
  • 2
  • 23
  • 36
  • With or within synchronization? – abc32112 Nov 25 '14 at 16:38
  • Hmm, not getting it. What happens if an item is removed after the iterator calls hasNext()? I don't see how this resolves the concurrency problem. – abc32112 Nov 25 '14 at 16:49
  • 1
    This does not provide an answer to the question. To critique or request clarification from an author, leave a comment below their post. – gipinani Nov 25 '14 at 17:09
  • @gipinani Why do you say it does not provide an answer? He is doing a for loop, modifies the list and has a ConcurrentModificationException. By using an iterator and the add/remove methods he could change the list while iterating – andrei Nov 25 '14 at 17:35
  • I tried that but unfortunately the iterator has the same concurrency problem when removing items. I ended up spamming "synchronised" all over the place, which seems to have resolved the issue, although my understanding of the keyword is still so so. – abc32112 Nov 25 '14 at 17:52
  • @schopy because just as a good question has code, so should a good answer. This answer is of no use to someone who doesn't know what an iterator is for example. – djv Nov 25 '14 at 19:17