You have in your hands the good old conditions of the race.
Your first Thread , with the exception of adding the first element to your Vector , serves absolutely no purpose. You can replace it with
obj.a.add("first");
Beef, as others have noted, is here
Iterator itr = obj.a.iterator(); while (itr.hasNext()) { obj.a.add("TEST");// java.lang.OutOfMemoryError: Java // heap space // itr.remove(); //java.lang.IllegalStateException }
itr.hasNext() is implemented as
public boolean hasNext() { return cursor != elementCount; }
If the cursor starts at 0 and elementCount is the size of your Vector . This call will never return false . Your while with the loop, adding elements until the program runs out of memory. cursor never moves forward because you never call next() . If you call next() when adding elements directly to Vector , you will get a ConcurrentModificationException .
source share