Use ThreadLocalRandom instead of Math.random() (#11165)

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.
This commit is contained in:
Dmitriy Dumanskiy 2021-04-19 14:56:16 +03:00 committed by GitHub
parent 976486f021
commit 3b89ac7cf0
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 4 additions and 2 deletions

View File

@ -57,6 +57,7 @@ import io.netty.buffer.ByteBuf;
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;
@ -178,7 +179,7 @@ public class WebSocket08FrameEncoder extends MessageToMessageEncoder<WebSocketFr
// 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);

View File

@ -26,6 +26,7 @@ import io.netty.handler.codec.http.HttpHeaders;
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;
@ -254,7 +255,7 @@ public class WebSocketClientHandshaker00 extends WebSocketClientHandshaker {
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;