If a BlockingInputStream input has a capacity of 8000 and we're calling input.read(buf, 0, buf.length) on a user buffer of 10000 with 14000 bytes added to input, then the following can happen:
- input reads the first 8000 bytes and copies them to the user's buffer
- The write position for the user's buffer is now at 8000 and the max number of bytes to be added is 2000 bytes, even if we have another 6000 bytes !
- Instead of adding another 2000 bytes, we add another 6000 bytes, leading to an ArrayIndexOutOfBoundsException
SOLUTION: the length of the remaining bytes has to be min(available, remaining space in user's buffer).
The unit test is BlockingInputStreamTest.testWritingBeyondLength()