Java.util.ConcurrentModificationException problem

In this code, I get java.util.ConcurrentModificationException, the method is in the web service and first reads the file and checks if the vakNaam file is in the file. It will then be deleted and the file will be overwritten. Exception thrown by Exception2 (in println)

@WebMethod public boolean removeVak(String naam){ ArrayList<String> tempFile = new ArrayList<String>(); //Read the lines boolean found = false; BufferedReader br = null; try { br = new BufferedReader(new FileReader("C:/vak.txt")); String strLine; while ((strLine = br.readLine()) != null){ tempFile.add(strLine); } }catch(Exception e){ System.out.println("Exception " + e); }finally { try { if (br != null) br.close(); } catch (Exception ex) { ex.printStackTrace(); } } //Write the lines BufferedWriter out= null; try{ for(String s : tempFile){ String [] splitted = s.split(" "); if(splitted[0].equals(naam)){ tempFile.remove(s); found = true; } } out = new BufferedWriter(new FileWriter("C:/vak.txt", false)); for(String s: tempFile){ out.newLine(); out.write(s); } out.close(); } catch (Exception e) { System.out.println("Exception2 " + e); return false; }finally { try { if (out != null) out.close(); } catch (Exception ex) { ex.printStackTrace(); } } return found; } 
+6
source share
2 answers

The error in this part:

 for(String s : tempFile){ String [] splitted = s.split(" "); if(splitted[0].equals(naam)){ tempFile.remove(s); found = true; } } 

Do not modify the list you are repeating. You can solve this problem using Iterator :

 for(Iterator<String> it = tempFile.iterator; it.hasNext();){ String s = it.next(); String [] splitted = s.split(" "); if(splitted[0].equals(naam)){ it.remove(); found = true; } } 
+20
source

The loop supported by Java 5 uses an iterator below it. That way, when you remove tempFile, the unsuccessful nature takes effect and throws a Concurrent exception. Use an iterator and call its delete method, which will be removed from the base collection.

+5
source

Source: https://habr.com/ru/post/887614/


All Articles