-1

I am getting an concurrent modification error while editing an XML file using Java in a JSP file. How is this caused and how can I solve it?

ElementFilter f = new ElementFilter("rurl-link");
Iterator subchilditr = childNode.getDescendants(f);

while (subchilditr.hasNext()) { // Exception is thrown here.
    Element subchild = (Element) subchilditr.next();

    if (subchild.getText().equalsIgnoreCase(prevtext)) {
        subchild.setText(link);
        out.println("Updated");
    }
}

This is the stacktrace:

java.util.ConcurrentModificationException
    java.util.AbstractList$Itr.checkForComodification(AbstractList.java:372)
    java.util.AbstractList$Itr.next(AbstractList.java:343)
    org.jdom.DescendantIterator.next(DescendantIterator.java:134)
    org.jdom.FilterIterator.hasNext(FilterIterator.java:91)
    org.apache.jsp.rurl_005fchangelink_005fxml_jsp._jspService(rurl_005fchangelink_005fxml_jsp.java:101)
    org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
    org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:386)
    org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:313)
    org.apache.jasper.servlet.JspServlet.service(JspServlet.java:260)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
Maverick
  • 2,738
  • 24
  • 91
  • 157
  • this is not nearly enough information – Travis Webb Mar 25 '11 at 00:26
  • I have added the stack trace too. – Maverick Mar 25 '11 at 00:30
  • While not enough say for sure, a concurrent modification exceptions means you changed the count of descendants of that childNode object while iterating it. Modifying a sequence while iterating a sequence like this is not recommended. – Vetsin Mar 25 '11 at 00:31
  • Writing Java code incorrectly inside a JSP file instead of a Java class doesn't make it a JSP problem. You would have exactly the same problem when doing it in a normal Java class. I removed the JSP tag since that's not related to the cause of the particular problem. – BalusC Mar 25 '11 at 00:58

1 Answers1

0

I believe you're using the JDOM library? You need to modify subchild outside of the iterator loop:

ElementFilter f = new ElementFilter("rurl-link");
Iterator subchilditr = childNode.getDescendants(f);
List<Element> subchildList = new ArrayList<Element>();

while (subchilditr.hasNext()) {
    Element subchild = (Element) subchilditr.next();

    if (subchild.getText().equalsIgnoreCase(prevtext)) {
        subchildList.add(subchild);
    }
}

for (Element subchild : subchildList) {
    subchild.setText(link);         
}
WhiteFang34
  • 70,765
  • 18
  • 106
  • 111