title: java.lang.ArrayIndexOutOfBoundsException: -1
body: <p>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.</p>
  
  <p>But after a few attempts the thread gets blocked and shows the following exception:</p>
  
  <pre><code>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)
  </code></pre>
  
  <p>After this exception the application terminates itself. How to solve this problem?</p>
  
  <p>How can I synchronize these two threads in two different Java classes?</p>