2

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?

5
  • Can you please show us your codes ? Commented Jul 3, 2013 at 7:14
  • what is the size of 'elementData' at that time.can u debug Commented Jul 3, 2013 at 7:16
  • its a big application so i cant share it Commented Jul 3, 2013 at 7:18
  • @rachana, in that case we can't help you properly Commented Jul 3, 2013 at 7:18
  • sounds like a race condition en.wikipedia.org/wiki/Race_condition Commented Jul 3, 2013 at 7:20

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

3 Comments

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

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.