Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Conversation

pratt4
Copy link
Contributor

@pratt4 pratt4 commented May 7, 2025

Fixes #2042

This is a typical TOCTOU (time-of-check/time-of-use) race https://en.wikipedia.org/wiki/Time-of-check_to_time-of-use.
The NPE was occurring because the channel field could be set to null by another thread between the check and its use:

if (channel != null) { // time-of-check
Channels.setDiscard(channel); // time-of-use
Channels.silentlyCloseChannel(channel);
}

By copying channel into a local variable in one atomic read, we ensure that—even if another thread changes the field—the local reference remains valid.

P.S. It is hard to write a deterministic test that fails consistently, so this PR only includes the code fix.

@pratt4
Copy link
Contributor Author

pratt4 commented May 9, 2025

HI @hyperxpro ...
can you please review this pr whenever you get time?

@hyperxpro hyperxpro requested a review from Copilot May 9, 2025 17:28
Copy link
Contributor

@Copilot Copilot AI left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull Request Overview

This PR fixes a race condition that could lead to a NullPointerException when cancelling a response by copying the channel reference to a local variable.

  • Introduces a local variable "ch" to capture the channel in one atomic operation.
  • Prevents a TOCTOU race condition by ensuring the local reference remains valid during subsequent operations.

@hyperxpro hyperxpro merged commit 73911eb into AsyncHttpClient:main May 9, 2025
3 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

NPE in at org.asynchttpclient.netty.channel.Channels.setAttribute(Channels.java:36)
2 participants