• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

ConcurrentModificationExc

 
Bodenstab Oliver
Ranch Hand
Posts: 47
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hallo,

i need your help!

I have a static cache database from type vector. One thread iterate over the cache database while an other thread remove one entry. The iterating thread get a ConcurrentModificationException.

How can i solve this problem

Please Help!

Oliver
 
John Smith
Ranch Hand
Posts: 2937
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Although Vector is a synchronized list, it's not thread safe for iteration through its elements. To avoid the ConcurrentModification exception, the iteration should be done in the synchronized block.
 
Lars Vonk
Ranch Hand
Posts: 30
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello Oliver,

One way to solve it is this:

synchronized(myVector) {
//Iterate myVector here
}

This way your Vector cannot be modified while iterating over it.

Cheers,
Lars
 
Andrew Monkhouse
author and jackaroo
Marshal Commander
Pie
Posts: 12014
220
C++ Firefox Browser IntelliJ IDE Java Mac Oracle
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Oliver,

Another way is to do something like:(Note: I am guessing at what you put into your Vector - you may have to change the definition of records to suit your implementation.) This has the advantage that you are synchronizing on myVector for the shortest possible time, then doing the work on a local snapshot of myVector.

You could also use the clone() method to create a local copy of myVector - from memory the clone method does a deep copy (Vector overrides clone for just this purpose) - then you could iterate over the local copy in the same way that I used the array (but the array would probably be faster - it then becomes more of a code readability issue).

Origanally posted by John Smith
Although Vector is a synchronized list, it's not thread safe for iteration through its elements.
The synchronization on Vector is usually not much help to the programmer, and we generally recommend against using it. Perhaps you could mention why you need a synchronized collection, and we can comment on whether Vector suits your purpose?

Regards, Andrew
 
Bodenstab Oliver
Ranch Hand
Posts: 47
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you all for advice!

I take the following solution.


The clone method only does a flat copy not a deep!
But i think, flat is good for this problem and with this solution the time of synchronizing is very minimal (clone-method is synchronized).

If someone have remarks to this solution, please let me know

Oliver
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic