I am trying to understand how ArrayList is not thread safe through a java program.Attached is my program.
import java.util.ArrayList;
import java.util.List;
public class class1
{
static List ar=new ArrayList(1);
public static void main(String[] args) throws InstantiationException,
IllegalAccessException, ClassNotFoundException, InterruptedException
{
Thread t1= new Thread()
{
public void run()
{
while(true)
{
ar.add(new Object());
}
}
};
Thread t2=new Thread()
{
public void run()
{
while(true)
{
ar=new ArrayList(1);
ar.add(new Object());
ar.add(new Object());
}
}
};
t1.start();
Thread.sleep(100);
t2.start();
}
}
The error i got is:
Exception in thread "Thread-0" java.lang.ArrayIndexOutOfBoundsException: 2
at java.util.ArrayList.add(Unknown Source)
at class1$1.run(class1.java:22)
I understand that the exception is caused by a thread.However,I am not getting a broader picture on how it is actually functioning.Any help would be highly appreciated.