java.lang.ArrayIndexOutOfBoundsException: -1

11,407

Solution 1

java.lang.ArrayIndexOutOfBoundsException is caused by the code trying to access a certain array value which does not exist.

For example:

String[] myArray = new String[5];

for(int i = 0; i < myArray.length; i++) {
    myArray[i] = "Value: " + i;
}

System.out.println(array[6].toString());

Since your array is only 5 long, and you're trying to access the 6th which doesn't exist, you'll get an exception.

Solution 2

if your trying to read the same file make sure you have synchronized your threads on the same object, when accessing a shared resource. this may throw ArrayIndexOutOfBoundsException

Share:
11,407
rachana
Author by

rachana

Updated on June 04, 2022

Comments

  • rachana
    rachana almost 2 years

    I have one Java application which contains two threads created in different Java classes. One thread is used to write an image file and another is reading the same file at the same time. Both threads are running simultaneously.

    But after a few attempts the thread gets blocked and shows the following exception:

    java.lang.ArrayIndexOutOfBoundsException: -1
    at java.util.ArrayList.elementData(ArrayList.java:371)
    at java.util.ArrayList.get(ArrayList.java:384)
    at com.sun.imageio.plugins.jpeg.JPEGImageReader.checkTablesOnly(JPEGImageReader.java:373)
    at com.sun.imageio.plugins.jpeg.JPEGImageReader.gotoImage(JPEGImageReader.java:476)
    at com.sun.imageio.plugins.jpeg.JPEGImageReader.readHeader(JPEGImageReader.java:597)
    at com.sun.imageio.plugins.jpeg.JPEGImageReader.readInternal(JPEGImageReader.java:1054)
    at com.sun.imageio.plugins.jpeg.JPEGImageReader.read(JPEGImageReader.java:1034)
    at javax.imageio.ImageIO.read(ImageIO.java:1448)
    at javax.imageio.ImageIO.read(ImageIO.java:1308)
        at java.lang.Thread.run(Thread.java:722)
    

    After this exception the application terminates itself. How to solve this problem?

    How can I synchronize these two threads in two different Java classes?

  • rachana
    rachana almost 11 years
    I have two threads in two different java classes. How can I synchronize them? Could you guide me to some example?
  • JREN
    JREN almost 11 years
    That's a completely different issue, but you should check out this link: docs.oracle.com/javase/tutorial/essential/concurrency/sync.h‌​tml
  • Austin A
    Austin A about 9 years
    @JREN Just being technical, but array[6].toString() would access the 7th item in myarray[] ;)