Reputation: 21
Lately i was playing around with semaphores and multithreading, when i noticed, that something weird is going on with array list. More details:
I have some class with a single private ArrayList:
public class NewClass{
private ArrayList list = new ArrayList();
public void put(Object val){
list.add(val);
}
public void del(Object val){
list.remove(val);
}
}
From some thread, i'm trying to remove elements from it (without putting anything before that):
public class SomeClass {
public static void main(String[] args) throws InterruptedException {
new SomeClass();
}
public SomeClass() throws InterruptedException {
Thread tr2 = new Thread() {
@Override
public void run() {
NewClass nc = new NewClass();
for (int i = 0; i < 100; i++) {
nc.del(i);
}
}
};
tr2.start();
}
}
And when the thread starts working - i have no errors, no exceptions, etc. While, if debugging, i can clearly see, that list.indexOf(val); return -1 value - it actually does not exist, but is "removed". Can anyone explain what is going on here?
Upvotes: 1
Views: 3085
Reputation: 12160
when you call remove, the list will become shorter than before. do you think your loop code is right? The total length is not 100 any more.
Upvotes: 0
Reputation: 2444
Like as you said "playing around with stuff".
Am suspecting you have been caught between the two methods of ArrayList.
public E remove(int index) // throws exception
and
public boolean remove(Object o) // doesn't throws exception
When you are accessing through it thread you are actually passing it like an reference as an object. which actually calls the remove(Object o) method which doesn't throw exception.
While i think while playing around from single thread program you directly calling
list.remove(int) /// method which actually throws IndexOutOfBoundsException.
Thisis just my assumption as you haven't provided the code where it throws exception
Upvotes: 0
Reputation: 328855
Too long for a comment:
NewClass
instances are not shared across threads and each instance is accessed from only one thread.List.remove(int index)
on an empty list does nothing special (it returns -1).Upvotes: 0
Reputation: 73568
Lists don't throw exceptions if you try to remove things that aren't in it with the remove(Object o) method. They return false.
Upvotes: 2