I have a MyObject() extends Thread
which creates a new MyObject
of itself in the run()
method.
This object has a List<E>
as a member, where I delete from under certain conditions.
I when creating the new Object I call start()
afterwards to start it's run method. But as soon as I spawn the new Object, it throws an
Exception in thread "Thread-1" java.lang.UnsupportedOperationException
at java.base/java.util.ImmutableCollections.uoe(ImmutableCollections.java:73)
at java.base/java.util.ImmutableCollections$AbstractImmutableCollection.remove(ImmutableCollections.java:80)
at mypackage.MyMainClass.MyObject.run(MyObject.java:87) <- here I remove from my List
Example:
public class MyObject extends Thread {
List<SomeType> list = new ArrayList<SomeType>();
SomeType st;
public MyObject(SomeType st) {
this.st = st;
// returns a List of SomeType
list = st.getList();
}
@Override
public void run() {
while(!done) {
SomeType toDelete;
if (condition) {
toDelete = st.getToDelete();
}
// Checks for null etc are done and not important
for (SomeType sometype : list) {
if (somecondition) {
// toDelete is always in that List
list.remove(toDelete)
}
}
if (lastcondition) {
MyObject newObject = new MyObject(this.st);
newObject.start();
}
}
}
}
Why do I get this error? Since the List is a member of each instance of the Object, why is it immutable for the new Threads, but not for my initial object?