My previous question led me to this question.
Is adding a function to an ArrayList stream safe?
I made an example application with the following classes
import java.util.ArrayList; import java.util.List; public class ThreadTest { public static List<DummyObject> list = null; public static boolean isLoaded = false; public static void main(String [] args) { MyThread t1 = new MyThread(1); MyThread t2 = new MyThread(2); t1.start(); t2.start(); } public static void loadObject(){ if(isLoaded){ return; } isLoaded = false; try{ list = new ArrayList<DummyObject>(); for(int i=0;i<10;i++){ list.add(i,new DummyObject()); }} catch(Exception e){ e.printStackTrace(); } isLoaded = true; } }
These are my flows
public class MyThread extends Thread { int threadNumber ; public MyThread(int threadNumber) { this.threadNumber = threadNumber; } @Override public void run() { try { sleep(10-threadNumber); } catch (InterruptedException e1) {
This is my dummy class.
public class DummyObject { }
Despite the fact that I was not able to throw the Null Pointer Exception that I received in the previous question the previous question , sometimes I get this error
Exception in thread "Thread-1" java.lang.IndexOutOfBoundsException: Index: 1, Size: 10 at java.util.ArrayList.add(ArrayList.java:367) at ThreadTest.loadObject(ThreadTest.java:25) at MyThread.run(MyThread.java:20)
The ArrayList Code form is a string that throws an error:
if (index > size || index < 0) throw new IndexOutOfBoundsException( "Index: "+index+", Size: "+size);
But, as can be seen from Exception , the index is 1 and the size is 10 , so there is no way for the condition to be satisfied. My assumption is true that adding the arrayList function is thread unsafe or is something else happening here?
source share