Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

RealBufferedSource.read() with length=0 blocks until there's some data, breaking InputStream.readNBytes #1476

Closed
cgrushko opened this issue May 6, 2024 · 2 comments · Fixed by #1479

Comments

@cgrushko
Copy link

cgrushko commented May 6, 2024

Repro:

Pipe p = new Pipe(1000);
Okio.buffer(p.sink()).write(new byte[10]).flush();

// This will block indefinitely:
Okio.buffer(p.source()).inputStream().readNBytes(10);

The code in JDK 21+35 LTS is:

while ((n = read(buf, nread,
     Math.min(buf.length - nread, remaining))) > 0) {
  nread += n;
  remaining -= n;
}

which effectively calls

read(buf, 0, 10) --> returns 10, do another iteration
read(buf, 10, 0) --> gets stuck

IMO it's a reasonable implementation of readNBytes.

When we call read(0), RealBufferedSource.read() will call PipeSource.read(8192), which will block as it should.
If RealBufferedSource.read() could return immediately when length=0, we won't get blocked.

@cgrushko cgrushko changed the title PipeSource.read() with length=0 blocks until there's some data RealBufferedSource.read() with length=0 blocks until there's some data, breaking InputStream.readNBytes May 6, 2024
@swankjesse
Copy link
Member

Yeah, good advice. Wanna send a pull request? Otherwise I’m happy to fix it.

@cgrushko
Copy link
Author

cgrushko commented May 7, 2024

Yeah, good advice. Wanna send a pull request? Otherwise I’m happy to fix it.

It's a bit of a process to get the CLA signed for me, so I'd appreciate if you could take it.
Also would like to take the opportunity to thank you folks for writing and maintaining okio and okhttp - it's an amazing piece of software :)

swankjesse added a commit that referenced this issue May 9, 2024
swankjesse added a commit that referenced this issue May 9, 2024
* Don't block on 0-byte reads

Closes: #1476

* Fixup another test
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging a pull request may close this issue.

3 participants