Skip to content

Commit

Permalink
Use ThreadLocalRandom instead of Math.random() (#11165)
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
doom369 committed Apr 19, 2021
1 parent 976486f commit 3b89ac7
Show file tree
Hide file tree
Showing 2 changed files with 4 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToMessageEncoder;
import io.netty.handler.codec.TooLongFrameException;
import io.netty.util.internal.PlatformDependent;
import io.netty.util.internal.logging.InternalLogger;
import io.netty.util.internal.logging.InternalLoggerFactory;

Expand Down Expand Up @@ -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(Integer.MAX_VALUE);
mask = ByteBuffer.allocate(4).putInt(random).array();
buf.writeBytes(mask);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@
import io.netty.handler.codec.http.HttpMethod;
import io.netty.handler.codec.http.HttpResponseStatus;
import io.netty.handler.codec.http.HttpVersion;
import io.netty.util.internal.PlatformDependent;

import java.net.URI;
import java.nio.ByteBuffer;
Expand Down Expand Up @@ -254,7 +255,7 @@ private static String insertRandomCharacters(String key) {
char[] randomChars = new char[count];
int randCount = 0;
while (randCount < count) {
int rand = (int) (Math.random() * 0x7e + 0x21);
int rand = PlatformDependent.threadLocalRandom().nextInt(0x7e) + 0x21;
if (0x21 < rand && rand < 0x2f || 0x3a < rand && rand < 0x7e) {
randomChars[randCount] = (char) rand;
randCount += 1;
Expand Down

0 comments on commit 3b89ac7

Please sign in to comment.