Skip to content

NativeEndpointConnection.read(ByteBuffer) does not return -1 at end of stream, breaking Java conventions #65

@fabiojo7777777

Description

@fabiojo7777777

Hi there,

While analyzing the code of the read(ByteBuffer) method in the NativeEndpointConnection class, I noticed a behavior that may be unexpected for most Java developers.

In Java, it's a well-established convention that when reading data from an InputStream or similar abstraction, the read method returns -1 to indicate the end of the stream. A return value of 0 typically means no data was read, but the stream remains open.

This pattern is so common that most Java developers rely on it instinctively. For example:

int bytesRead = 0;
while (bytesRead != -1) {
  bytesRead = connection.read(buffer);
  buffer.clear();
}

In the case of NativeEndpointConnection, however, in the read(ByteBuffer) method, if the internal native readNative method returns -1, the subsequent call to dst.limit(sz) in read(ByteBuffer) will throw an IllegalArgumentException, since ByteBuffer.limit(int) does not accept negative values. This results in an exception being thrown instead of signaling end-of-stream via a -1 return value — effectively breaking the expected control flow.

Even though this class does not implement InputStream or ReadableByteChannel and is technically not required to follow those APIs, it does define a read(ByteBuffer) method that closely resembles them. As such, most developers will naturally assume it adheres to the same semantics.

Java is known for its consistency and predictable behavior due to strong conventions. This deviation from the expected read behavior may lead to subtle bugs or infinite loops for developers who aren't aware of this implementation detail.

It would be great if the method could be adjusted to return -1 on end-of-stream, or at the very least, documented clearly so that developers using the API can code accordingly.

Thanks for your work on this project!

@fabiojo7777777

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions