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

Use ThreadLocalRandom instead of Math.random() #11165

Merged
merged 2 commits into from
Apr 19, 2021

Conversation

doom369
Copy link
Contributor

@doom369 doom369 commented Apr 17, 2021

Motivation:

ThreadLocalRandom doesn't cause contention. Also nextInt() generates only 4 random bytes while Math.random() generates 8 bytes.

Modification:

Replaced (int) Math.random() with PlatformDependent.threadLocalRandom().nextInt()

Result:

No possible contention when random numbers for WebSockets.

@@ -178,7 +179,7 @@ protected void encode(ChannelHandlerContext ctx, WebSocketFrame msg, List<Object

// Write payload
if (maskPayload) {
int random = (int) (Math.random() * Integer.MAX_VALUE);
int random = PlatformDependent.threadLocalRandom().nextInt();
Copy link
Contributor

Choose a reason for hiding this comment

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

This was previously never negative but now it can be. That won't be a problem, right?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

From what I know it's not a problem. But that's a good point. Who knows, maybe someone already expects it to be positive :). So let's preserve the prev behavior just in case.

@chrisvest chrisvest merged commit 3b89ac7 into netty:4.1 Apr 19, 2021
chrisvest pushed a commit that referenced this pull request Apr 19, 2021
Motivation:

`ThreadLocalRandom` doesn't cause contention. Also `nextInt()` generates only 4 random bytes while `Math.random()` generates 8 bytes.

Modification:

Replaced `(int) Math.random()` with `PlatformDependent.threadLocalRandom().nextInt()`

Result:

No possible contention when random numbers for WebSockets.
@chrisvest
Copy link
Contributor

@doom369 Thanks!

raidyue pushed a commit to raidyue/netty that referenced this pull request Jul 8, 2022
Motivation:

`ThreadLocalRandom` doesn't cause contention. Also `nextInt()` generates only 4 random bytes while `Math.random()` generates 8 bytes.

Modification:

Replaced `(int) Math.random()` with `PlatformDependent.threadLocalRandom().nextInt()`

Result:

No possible contention when random numbers for WebSockets.
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.

None yet

3 participants