On this code I get an java.util.ConcurrentModificationException the method is in a webservice and first reads the file and checks if the vakNaam is in the file. Then it will be removed and the file will be rewritten. The exception is thrown by Exception2 (in the 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;
}
How do you fix Java's ConcurrentModificationException? There are two basic approaches: Do not make any changes to a collection while an Iterator loops through it. If you can't stop the underlying collection from being modified during iteration, create a clone of the target data structure and iterate through the clone.
If a thread modifies a collection directly while it is iterating over the collection with a fail-fast iterator, the iterator will throw this ConcurrentModificationException.
Every stream is backed by Spliterator . If spliterator has no IMMUTABLE and CONCURRENT characteristics, then, as documentation says: After binding a Spliterator should, on a best-effort basis, throw ConcurrentModificationException if structural interference is detected.
The error is in this part:
for (String s : tempFile){
String [] splitted = s.split(" ");
if (splitted[0].equals(naam)){
tempFile.remove(s);
found = true;
}
}
Don't modify the list you are iterating over. You could solve this by using the Iterator
explicitely:
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;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With