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:
parent
976486f021
commit
3b89ac7cf0
@ -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);
|
||||
|
||||
|
@ -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;
|
||||
|
Loading…
Reference in New Issue
Block a user