I am having trouble with my collecitons. My program exists in a multithreaded environment so I must protect them. So access to modify the collection is synchronized. But iteration is a form of access, and iteration is not synchronized. Even on Collections.synchronizedXXX the iteration is not synchornized.
My collections are not meant to be modified outside of their parent. so iterator#remove will not be used.
So at this point I see 3 options.
1. Don't return iterators, but return a copy of the Collection. Or return an iterator over a copy of the collection. Where the copy was created while the collection was locked.
2. create a locking scheme that locks the collection while one iterates over it, and then release the lock when one is done iterating. This is cheaper since i won't have to copy the collection.
3. If concurrent modification exception is thrown during iteration, catch it and restart the iteration. But this seems unsafe as the exception unexplainably is best effort!?
I used to return arrays instead of collecitons. In anticipation of a move to 1.5 i started returning collecitons. Plus with arrays you can only be sure of what will come out of it, not what you can put into it. With generics there will be safety both ways. But here these collections are intended to be unmodifiable (or return copy) and nothing can be put into them.
There is only 1 use for the returned collections and that is to see all the elements in it.
Looking for the cheapest way. Of course it has to be 100% safe.
Any tips here? Thanks in advance
[ November 06, 2005: Message edited by: Mr. C Lamont Gilbert ]