We help IT Professionals succeed at work.

Potential for IndexOutOfBoundException

onaled777 asked
I am currently looking into the potential for an IndexOutOfBoundException. I am examing the code below because it reoccurs pretty frequently.

				byte[] arr = new byte[2048];
				int length = 0;
				while ((length = pdfInputStream.read(arr)) > 0) {
					response.getOutputStream().write(arr, 0, length);  //

Open in new window

Does code like this have the potential to throw an IndexOutOfBoundsException?  My thought is yes because the Arrays are not synchronized. I would prefer some verification.
Watch Question

Senior Java Architect
That array is a local variable, which is never shared between threads, so you don't have to worry about synchronization. That code looks safe, to me.


Thank you!
Top Expert 2016

If off is negative, or len is negative, or off+len is greater than the length of the array b, then an IndexOutOfBoundsException is thrown.
(API docs for OutputStream.write)

There is no connection between synchronization and such an exception. The way the code is currently written can not cause the violations mentioned above