Reputation: 1091
Lets say I have a list returned by an arbitrary method:
List<E> someList = someObject.getList();
someList
can be changed at any time by someObject
in another thread. I have no access to the implementation of someObject
, and someObject.getList()
does not return a synchronized or immutable list implementation.
I want to iterate through someList
. Unfortunately, since the list can be changed, iterating through it normally doesn't work:
// Sometimes throws ConcurrentModificationException
for(E element : someObject.getList()) {
doSomething(element);
// ...
}
So how can I iterate through a list (not thread safe) returned by an alien method?
Upvotes: 7
Views: 140
Reputation: 1221
Maybe the other thread uses a synchronization mechanism like synchronized(list) for modifying the list; in that case you could use synchronized on the same object and you'd be safe.
List<E> list=someobject.getList();
synchronized (list) {
for (E element : list) {
doSomething(element);
}
}
You can try synchronizing on the list or on someObject and hope it works.
Other than that, I don't see any clean solution. In the end, if the other code that modifies the list doesn't care about other users of the list, it's pretty impossible to iterate safely.
Unclean one: try to copy the array in a loop until the ConcurrentModificationException is not thrown anymore.
Upvotes: 1