[Networking] More reliable fix to prevent null networkhandler #55
+84
−24
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
With threaded networking, custom payload packets can be received and handled on the network thread, where Minecraft.getNetworkHandler() may return null due to a race condition the handler that delivered the packet may not yet be (or may no longer be) assigned on the Minecraft instance. The previous fix of deferring to the main thread via ensureOnMainThread() didn't fully solve this either, since the handler could still be nulled out between ticks. This fix instead captures the network handler at packet arrival time where it is guaranteed to be non-null and stores it in the Context object and a ThreadLocal so that it is available when sending response packets from within a listener callback. A ThreadLocal is used rather than threading the handler through as a method parameter because sendPacket() is reached through the public send/sendNoCheck API, and changing those signatures would break the end-user API.
I reverted the now unnecessary ensureOnMainThread with this commit/pr as well, which only partially resolved the issue.
I investigated other places where null network handler may be an issue, but the other uses of minecraft.getNetworkHandler() are covered by null checks in isPlayReady, so it's good to go.