2

Getting below exception on ArrayList.clear() Any reason why would clear throw such exception. I know add or get might throw this for negative index or larger thn list size.

Fatal Exception: java.lang.ArrayIndexOutOfBoundsException: length=49; index=49
       at java.util.ArrayList.clear(ArrayList.java:569)
David Soroko
  • 8,521
  • 2
  • 39
  • 51
Balwinder SIngh
  • 1,831
  • 2
  • 24
  • 28
  • 1
    Could please share a piece of code that reproduces the problem? – Joffrey Sep 22 '21 at 07:57
  • 4
    Do you by any chance modify the list concurrently? – Joffrey Sep 22 '21 at 07:58
  • Length is 49, and index starts at 0, so the maximum index is 48. https://stackoverflow.com/a/32568266/4161471 https://stackoverflow.com/q/5554734/4161471 – aSemy Sep 22 '21 at 08:23
  • 1
    Does this answer your question? [What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?](https://stackoverflow.com/questions/5554734/what-causes-a-java-lang-arrayindexoutofboundsexception-and-how-do-i-prevent-it) – aSemy Sep 22 '21 at 08:23
  • @aSemy this question is specifically asking about `clear()` and mentioning the OP knows about indices issues, so it's not really a duplicate IMO (there is no useful answer there regarding this specific problem, which is most likely caused by concurrency issues) – Joffrey Sep 22 '21 at 08:53

1 Answers1

5

The implementation of ArrayList is not thread safe by design. Specifically regarding clear(), the code assumes that the size of the list doesn't change while clear is executing.

Most likely, you have another thread that reduces the the list size concurrently with clear which causes the logic to try and access an index that is out of bounds.

David Soroko
  • 8,521
  • 2
  • 39
  • 51