CustomObject foundCustomObject = null;
while(true){
System.out.println(System.identityHashCode(staticClass.getArrayList()));
System.out.println(staticClass.getArrayList().size());
for(CustomObject customObject : staticClass.getArrayList()){
if(customObject.getCustomField().equals("")){
System.out.println("ADDED OBJECT FOUND!");
break;
}
}
if(foundCustomObject != null){
break;
}else{
try {
Thread.sleep((long) (Math.random() * 1000));
} catch (Exception e) {
e.printStackTrace();
}
}
}
I have two threads, one is running the above code. The second thread is doing the following when the user clicks a button in my application:
System.out.println("ADDING CUSTOM OBJECT TO LIST: "+System.identityHashCode(staticClass.getArrayList()));
boolean success = staticClass.getArrayList().add(new CustomObject(System.currentTimeMillis()));
System.out.println(success);
Every time the adding thread calls .add(), it returns true for success. However, sometimes the looping thread does not see the results of the .add() being called in the adding thread. By this, I mean that the size of the list does not increase and the object does not seem to actually be added as far as the looping thread knows. I am printing the memory addresses of the ArrayList in both threads to verify that they are the same. I don't understand how I can be calling .add() in one thread, checking the .size() in the other thread and not having it go up. If anyone has any idea why this behavior is occurring, please let me know.
EXAMPLE CONSOLE OUTPUT WHEN FAILING:
354613969
0
354613969
0
ADDING CUSTOM OBJECT TO LIST: 354613969
true
354613969
0
354613969
0