简体   繁体   中英

Iterating through alien list

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM