简体   繁体   中英

Two threads call same code even if it is synchronized

I get an exception:

Exception in thread "Thread-0" java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
    at java.util.ArrayList.rangeCheck(Unknown Source)
    at java.util.ArrayList.get(Unknown Source)

and the exception is when I try to remove element from the list then get the first one. The problem is that a thread want to access that first element when there is already no elements in the list. But I did put synchronized in method stub. What is wrong?

    private static ArrayList<Pracownik> LIST;
public static synchronized void roll(){

        if (LIST.size() > 0) {
            LISTA.remove(0);//removing from list
            String initials = LISTA.get(0).getInijcaly();   //here is exception 
        }

    }

This doesn't have to be a threading problem.

Look at the sequence of calls again:

// check that the list has at least 1 element
if (ISTA.size() > 0) {

    // remove 1 element
    LISTA.remove(0);

    // list might have 0 elements at this point
    LISTA.get(0);
}

Here you check that the list has at least 1 element, then remove an element, then try to retrieve another. This will throw an exception if the list's size was 1.

That's assuming that ISTA / LIST / LISTA are all the same thing and those are just typos. (Otherwise, if they are different, then you are checking the size of the wrong list...)

The snippet is too small to tell what the right way to fix it is and it should frankly be trivial for you to solve.

You either need to:

  • Check that the list has at least 2 things in it before accessing those 2 things.
  • Check that the has at least 1 thing and only access 1 thing.

This is a problem with the way you are trying to access the element. You can try using below approach.

 if (LISTA.size() > 0) {
        LISTA.remove(0);
        if(LISTA.size() >= 1){
            LISTA.get(0).getInijcaly();
        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM