简体   繁体   中英

IndexOutOfBoundsException when reading from stream

I wrote a Java method to send an instruction to a remote device via serial port and get a known number of bytes as the answer. The code runs on RaspberryPi, using librxtx-java library. The remote device was verified to send the answer of expected length.

The code below is the last part of this method where RaspberryPi waits for all the bytes of the answer for up to a given time "t_max".

The code as it is throws an IndexOutOfBoundsException during System.arraycopy . If I wrap the arraycopy instruction by try...catch and print out the pointer variable at catch, there is indeed an index overflow.

However, if I uncomment the line which prints out the pointer value, there is no more exception. Even replacing this line by System.out.println("X"); makes the exception gone, but not does the System.out.print("X"); for example.

I tried changing the variables to volatile but no more luck. How can printing out to terminal change the value of a variable?

long t0 = System.currentTimeMillis();
long t = t0;
byte[] answer = new byte[answerLength];
byte[] readBuffer = new byte[answerLength];
int numBytes = 0;
int answerPointer = 0;
while (t - t0 < t_max) {
    try {
        if (inputStream.available() > 0) {
            numBytes = inputStream.read(readBuffer);
        }
    } catch (Exception e) {
    }

    if (numBytes > 0) {
        // System.out.println("answerPointer="+answerPointer);
        System.arraycopy(readBuffer, 0, answer, answerPointer, numBytes);
        answerPointer = answerPointer + numBytes;
    }

    if (answerPointer == answerLength) {
        return (answer);
    }

    t = System.currentTimeMillis();
}

Have you tried verifying if the output stream and input stream are linked in any way? May be the input stream is reading from the output-stream and '\\n' (new line) is being used as the end of stream character. Can you try printing out to a print-stream wrappend around byte-array-output-stream instead of standard-out and see if doing a ps.println("X") causes an exception? If it does cause an exception then possibly the standard output and input stream are linked and that is why doing a System.out.println("X") makes the exception go away.

Also, volatile keyword is used in the context of threads. It will not have any effect in a single thread environment.

If the code inputStream.available() throws an exception on second iteration of while (t - t0 < t_max) variables numBytes and readBuffer stay initialized with old values. Try to wrap all code in block while (t - t0 < t_max) into try {} catch {} and don't hide an exception.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM