javamultithreadingarraylistcopyonwritearraylist

ArrayList, checking size on 2 threads


I have a list:

ArrayList list = new ArrayList<>();

On first thread I add elements (it is fast - 30/second) On the second thread I read its size and print to file.

First thread:

synchronized(list){
    list.add(PlayerPosition);
}

Second thread:

synchronized(list){
if(list.size()>0)
    out.print(list.size() + " ");
}

It is the output of the file, only a part: 1 1 1 3 3 5 4 6 7 7 9 11 8 9 12 10 14 16

It is wrong, cause it should only increase. There can be 1 1 1, but can't be 11 8.

My program is big, BUT these are only occurences of this list (I have removed half of the code to debug it). There are no list.remove() etc. in the whole app.

I have a question: is this possible, that it acts like this? Cause otherwise - it is my fault somewhere in the code.

And yeah, I have tried with CopyOnWriteArrayList - same thing. Thanks!


Solution

  • It's possible that the prints are not being executed in the order you expect. Change the code of the second thread to the following:

    synchronized(list){
        if (list.size() > 0) {
            synchronized (out) {
                out.print(list.size() + " ");
                out.flush();
            }
        }
    }
    

    Your OutputStream is writing out characters to the terminal (or a file, or something else). Without synchronizing on out and flushing, when Thread 2 tells the OutputStream to print, it's possible that the previous print has not finished yet. Synchronizing and flushing forces Thread 2 to wait until all the characters have actually been written to the terminal before continuing.