I have a class which extends LinkedList and implements Runnable. I also have a main class which modifies the extended LinkedList.
So, the issue is, the LinkedList is being modified by 2 threads:
main() in the main thread
and run() in the thread which is created from implementing Runnable
An example that I whipped up:
import java.util.LinkedList;
public class test2 {
MyList extendedList = new MyList();
public static void main(String[] args) {
test2 test = new test2();
test.extendedList.add("Hi!"); //modified here
new Thread(test.extendedList).start();
}
public class MyList extends LinkedList<String> implements Runnable {
public void run() {
while (true) {
for (String str : this) { //here is where it happens
System.out.println(str);
this.remove(str); //also modified here
}
}
}
}
}
The console output:
Hi!
Exception in thread "Thread-0" java.util.ConcurrentModificationException
at java.util.LinkedList$ListItr.checkForComodification(Unknown Source)
at java.util.LinkedList$ListItr.next(Unknown Source)
at test2$MyList.run(test2.java:16)
at java.lang.Thread.run(Unknown Source)
I'm pretty sure the reason this is happening is because I need to Synchronize the LinkedList. How would I do that if the LinkedList is being extended and not initialized elsewhere? Maybe its something else?