milgra
about
articles
projects
blogroll
bit-101
coding horror
blameit
failblog
beszeljukmac
sghu
navigation
posts
docs
admin
|
2009-05-16 Iteration hell
December 1st, 2009
|
a very common problem in java when you are iterating through some list, and an external thread or the thread itself wants to modify the underlying list
Source Code
to avoid concurrent modification exception, the most common solution is to use an iterator and add/delete the new element with it, or, if it is safe for the same thread, use synchronization to handle external threads.
my problem is that both solution needs too many cpu cycles.
for most cases, the solution below is the best :
Source Code
so if the original list is changed, we clone it before iterating through, and modification of the original array won’t affect iteration. but beware, its only good if a plus cycle doesn’t matter on the objects ( no destruction happens before removing the element ).
in those cases good old iterator has to be used.
MilGra
|
|