ConcurrentModificationException while iteratoring recursively

Usman Zafer :

I m writing a fucntion that will get me the list of sub folders in a given folder using their folder ids. Somehow, i am ending up with a java.util.ConcurrentModificationException.

private List<Long> getChildrenFolders(Long folderId) {
        List<Long> directChildren=new CopyOnWriteArrayList <>();
        Iterator<Folder> folderList= (Iterator<Folder>) folderMap.values().iterator();

        while (folderList.hasNext()){
            Folder currentFolder=folderList.next();
            Long parentId=currentFolder.getParentId();
            Long currentFolderId=currentFolder.getId();
            if(parentId.equals(folderId)){
                directChildren.add(currentFolderId);
                Folder folder=  actionManager.getFolderById(currentFolderId);
                folder.getParentId();
            }
        }

        CopyOnWriteArrayList<Long> copy= new CopyOnWriteArrayList<Long>(directChildren);

        Iterator<Long> directChildrenIterator = copy.iterator();

        while (directChildrenIterator.hasNext()){
            Long value=directChildrenIterator.next();
           directChildren.addall(getChildrenFolders(value));
        }
        return directChildren;
    }

However, I keep getting a ConcurrentModificationException error for the lines:

> while (directChildrenIterator.hasNext()){
> 
>         Long value=directChildrenIterator.next();

Any clue as to what I'm doing wrong here? Any help is much appreciated.

Jason :

You're creating an Iterator from the List of Longs then you're updating that first List inside of the Iterator. That is the causation of the ConcurrentModificationException.

One way to solve this, albeit cheap, is to create a separate list of Longs that are going to be added.

        List<Long> toAdd = new ArrayList<>();

        while (directChildrenIterator.hasNext()){
            Long value = directChildrenIterator.next();

            toAdd.addall(getChildrenFolders(value));
        }
        directChildren.addAll(toAdd);

        return directChildren;

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=217360&siteId=1