There are two threads A and B. A keeps writing to an ArrayList and B keeps reading from it. The following code is for reading the ArrayList and belongs to thread B.
The issue with this code is that sometimes both of the IF statements becomes true which should not be possible. First IF is there to ensure that list is not read beyond its size. Second IF is not a part of actual code. I have put it just for verification purposes. As you can see in the Output below, size of the list is greater than writeNext variable, I don't understand why this returns null. And yes, if I place a print statement or a a very small delay just after first IF, everything works fine. Please remember that there is just one thread that writes into the ArrayList, so issue should not be related to synchronization.
public void run() {// thread B
public class WriteTicksToFile implements Runnable, Serializable {
int writeNext = 0;
@Override
public void run() {
while (true) {
// read till writeNext is equal to ArrayList.size()-1 i.e. the last index
if (writeNext < TickData.getCompleteTickList().size()) {
// System.out.println(TickData.getCompleteTickList().size()+" "+writeNext);
if (TickData.getCompleteTickList().get(writeNext) == null) {
System.out.println("ListSize: " + TickData.getCompleteTickList().size() + " " + "Read@Index: " + writeNext);
}// if ends
// write element to file.
writeTick(TickData.getCompleteTickList().get(writeNext));
writeNext++;
}// if ends
}// while ends
}
}
Output:
Number of symbols found: 19
Market Opening time: 81500
Market Closing time: 235900
Current Time: 203931
Waiting for market to open...
Market Opened @ 203931
ListSize: 15876 Read@Index: 15875
ListSize: 15877 Read@Index: 15876