Skip to content

Commit

Permalink
Prefer JDK ThreadLocalRandom implementation over ours.
Browse files Browse the repository at this point in the history
Motivation:

We have our own ThreadLocalRandom implementation to support older JDKs . That said we should prefer the JDK provided when running on JDK >= 7

Modification:

Using ThreadLocalRandom implementation of the JDK when possible.

Result:

Make use of JDK implementations when possible.
  • Loading branch information
normanmaurer authored and Scottmitch committed Feb 16, 2017
1 parent 38496a2 commit fbf0e5f
Show file tree
Hide file tree
Showing 27 changed files with 92 additions and 65 deletions.
6 changes: 2 additions & 4 deletions buffer/src/test/java/io/netty/buffer/AbstractByteBufTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,8 @@
import io.netty.util.ByteProcessor;
import io.netty.util.CharsetUtil;
import io.netty.util.IllegalReferenceCountException;
import io.netty.util.internal.ThreadLocalRandom;
import io.netty.util.internal.PlatformDependent;
import org.junit.After;
import org.junit.Assume;
import org.junit.Before;
import org.junit.Test;

Expand All @@ -38,7 +37,6 @@
import java.nio.channels.ScatteringByteChannel;
import java.nio.channels.WritableByteChannel;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.Random;
import java.util.Set;
Expand Down Expand Up @@ -2126,7 +2124,7 @@ private void testInternalNioBuffer(int a) {
assertEquals(1, buf.remaining());

byte[] data = new byte[a];
ThreadLocalRandom.current().nextBytes(data);
PlatformDependent.threadLocalRandom().nextBytes(data);
buffer.writeBytes(data);

buf = buffer.internalNioBuffer(0, a);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@

package io.netty.buffer;

import io.netty.util.internal.ThreadLocalRandom;
import io.netty.util.internal.PlatformDependent;
import org.junit.Assume;

import static org.junit.Assert.assertEquals;
Expand All @@ -26,8 +26,8 @@ public class RetainedSlicedByteBufTest extends SlicedByteBufTest {
protected ByteBuf newBuffer(int length, int maxCapacity) {
Assume.assumeTrue(maxCapacity == Integer.MAX_VALUE);
ByteBuf wrapped = Unpooled.wrappedBuffer(new byte[length * 2]);
ByteBuf buffer = wrapped.retainedSlice(length > 1 ? ThreadLocalRandom.current().nextInt(length - 1) + 1 : 0,
length);
ByteBuf buffer = wrapped.retainedSlice(length > 1 ?
PlatformDependent.threadLocalRandom().nextInt(length - 1) + 1 : 0, length);
wrapped.release();

assertEquals(0, buffer.readerIndex());
Expand Down
5 changes: 3 additions & 2 deletions buffer/src/test/java/io/netty/buffer/SlicedByteBufTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
*/
package io.netty.buffer;

import io.netty.util.internal.ThreadLocalRandom;
import io.netty.util.internal.PlatformDependent;
import org.junit.Assume;
import org.junit.Ignore;
import org.junit.Test;
Expand All @@ -34,7 +34,8 @@ public class SlicedByteBufTest extends AbstractByteBufTest {
protected ByteBuf newBuffer(int length, int maxCapacity) {
Assume.assumeTrue(maxCapacity == Integer.MAX_VALUE);
ByteBuf buffer = Unpooled.wrappedBuffer(
new byte[length * 2], length > 1 ? ThreadLocalRandom.current().nextInt(length - 1) + 1 : 0, length);
new byte[length * 2], length > 1 ?
PlatformDependent.threadLocalRandom().nextInt(length - 1) + 1 : 0, length);
assertEquals(0, buffer.readerIndex());
assertEquals(length, buffer.writerIndex());
return buffer;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,9 @@
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.socket.InternetProtocolFamily;
import io.netty.util.internal.PlatformDependent;
import io.netty.util.internal.SocketUtils;
import io.netty.util.internal.StringUtil;
import io.netty.util.internal.ThreadLocalRandom;
import org.junit.Test;

import java.net.InetAddress;
Expand Down Expand Up @@ -143,6 +143,6 @@ private static void testIp(InetAddress address, int prefix) throws Exception {
}

private static int nextInt(int max) {
return ThreadLocalRandom.current().nextInt(0, max);
return PlatformDependent.threadLocalRandom().nextInt(max);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -34,8 +34,8 @@
import io.netty.handler.codec.http.HttpVersion;
import io.netty.handler.codec.http.LastHttpContent;
import io.netty.handler.stream.ChunkedInput;
import io.netty.util.internal.PlatformDependent;
import io.netty.util.internal.StringUtil;
import io.netty.util.internal.ThreadLocalRandom;

import java.io.File;
import java.io.IOException;
Expand Down Expand Up @@ -297,7 +297,7 @@ private void initMixedMultipart() {
*/
private static String getNewMultipartDelimiter() {
// construct a generated delimiter
return Long.toHexString(ThreadLocalRandom.current().nextLong()).toLowerCase();
return Long.toHexString(PlatformDependent.threadLocalRandom().nextLong()).toLowerCase();
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@
import io.netty.handler.codec.http.HttpRequestEncoder;
import io.netty.handler.codec.http.HttpResponseDecoder;
import io.netty.util.CharsetUtil;
import io.netty.util.internal.ThreadLocalRandom;
import io.netty.util.internal.PlatformDependent;
import org.junit.Test;

import java.net.URI;
Expand Down Expand Up @@ -102,7 +102,7 @@ protected WebSocketFrameEncoder newWebSocketEncoder() {
};

byte[] data = new byte[24];
ThreadLocalRandom.current().nextBytes(data);
PlatformDependent.threadLocalRandom().nextBytes(data);

// Create a EmbeddedChannel which we will use to encode a BinaryWebsocketFrame to bytes and so use these
// to test the actual handshaker.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,7 @@
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.embedded.EmbeddedChannel;
import io.netty.util.ReferenceCountUtil;
import io.netty.util.internal.ThreadLocalRandom;
import io.netty.util.internal.PlatformDependent;
import org.junit.Test;

import java.util.List;
Expand Down Expand Up @@ -217,7 +216,7 @@ protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) t
}
});
byte[] bytes = new byte[1024];
ThreadLocalRandom.current().nextBytes(bytes);
PlatformDependent.threadLocalRandom().nextBytes(bytes);

assertTrue(channel.writeInbound(Unpooled.wrappedBuffer(bytes)));
assertBuffer(Unpooled.wrappedBuffer(bytes), (ByteBuf) channel.readInbound());
Expand Down Expand Up @@ -249,7 +248,7 @@ protected void decodeLast(ChannelHandlerContext ctx, ByteBuf in, List<Object> ou
}
});
byte[] bytes = new byte[1024];
ThreadLocalRandom.current().nextBytes(bytes);
PlatformDependent.threadLocalRandom().nextBytes(bytes);

assertTrue(channel.writeInbound(Unpooled.wrappedBuffer(bytes)));
assertBuffer(Unpooled.wrappedBuffer(bytes, 0, bytes.length - 1), (ByteBuf) channel.readInbound());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,17 +15,17 @@
*/
package io.netty.handler.codec.compression;

import io.netty.util.internal.ThreadLocalRandom;
import java.util.Random;

public abstract class AbstractCompressionTest {

protected static final ThreadLocalRandom rand;
protected static final Random rand;

protected static final byte[] BYTES_SMALL = new byte[256];
protected static final byte[] BYTES_LARGE = new byte[256 * 1024];

static {
rand = ThreadLocalRandom.current();
rand = new Random();
fillArrayWithCompressibleData(BYTES_SMALL);
fillArrayWithCompressibleData(BYTES_LARGE);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,19 +22,19 @@
import io.netty.util.CharsetUtil;
import io.netty.util.ReferenceCountUtil;
import io.netty.util.internal.EmptyArrays;
import io.netty.util.internal.ThreadLocalRandom;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.util.Arrays;
import java.util.Random;

import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*;

public abstract class AbstractIntegrationTest {

protected static final ThreadLocalRandom rand = ThreadLocalRandom.current();
protected static final Random rand = new Random();

protected EmbeddedChannel encoder;
protected EmbeddedChannel decoder;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -132,8 +132,9 @@ public void testChecksumErrorOfLastBlock() throws Exception {
@Override
protected byte[] compress(byte[] data) throws Exception {
ByteArrayOutputStream os = new ByteArrayOutputStream();
int size = MAX_BLOCK_SIZE + 1;
LZ4BlockOutputStream lz4Os = new LZ4BlockOutputStream(os,
rand.nextInt(MIN_BLOCK_SIZE, MAX_BLOCK_SIZE + 1));
rand.nextInt(size - MIN_BLOCK_SIZE) + MIN_BLOCK_SIZE);
lz4Os.write(data);
lz4Os.close();

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,12 +22,13 @@
import io.netty.util.CharsetUtil;
import io.netty.util.ReferenceCountUtil;
import io.netty.util.internal.EmptyArrays;
import io.netty.util.internal.ThreadLocalRandom;
import io.netty.util.internal.PlatformDependent;
import org.junit.Test;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Random;
import java.util.zip.DeflaterOutputStream;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
Expand Down Expand Up @@ -82,7 +83,7 @@ public abstract class ZlibTest {
"</body></html>").getBytes(CharsetUtil.UTF_8);

static {
ThreadLocalRandom rand = ThreadLocalRandom.current();
Random rand = PlatformDependent.threadLocalRandom();
rand.nextBytes(BYTES_SMALL);
rand.nextBytes(BYTES_LARGE);
}
Expand Down
4 changes: 1 addition & 3 deletions common/src/main/java/io/netty/util/ResourceLeakDetector.java
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@

import io.netty.util.internal.PlatformDependent;
import io.netty.util.internal.SystemPropertyUtil;
import io.netty.util.internal.ThreadLocalRandom;
import io.netty.util.internal.logging.InternalLogger;
import io.netty.util.internal.logging.InternalLoggerFactory;

Expand All @@ -27,7 +26,6 @@
import java.util.ArrayDeque;
import java.util.Deque;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.atomic.AtomicBoolean;

import static io.netty.util.internal.StringUtil.EMPTY_STRING;
import static io.netty.util.internal.StringUtil.NEWLINE;
Expand Down Expand Up @@ -246,7 +244,7 @@ private DefaultResourceLeak track0(T obj) {
}

if (level.ordinal() < Level.PARANOID.ordinal()) {
if ((ThreadLocalRandom.current().nextInt(0, samplingInterval)) == 0) {
if ((PlatformDependent.threadLocalRandom().nextInt(samplingInterval)) == 0) {
reportLeak(level);
return new DefaultResourceLeak(obj);
} else {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -138,7 +138,7 @@ public static byte[] defaultMachineId() {
byte[] bestMacAddr = MacAddressUtil.bestAvailableMac();
if (bestMacAddr == null) {
bestMacAddr = new byte[EUI64_MAC_ADDRESS_LENGTH];
ThreadLocalRandom.current().nextBytes(bestMacAddr);
PlatformDependent.threadLocalRandom().nextBytes(bestMacAddr);
logger.warn(
"Failed to find a usable hardware address from the network interfaces; using random bytes: {}",
MacAddressUtil.formatAddress(bestMacAddr));
Expand Down
28 changes: 28 additions & 0 deletions common/src/main/java/io/netty/util/internal/PlatformDependent.java
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@
import java.util.Locale;
import java.util.Map;
import java.util.Queue;
import java.util.Random;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedDeque;
import java.util.concurrent.ConcurrentMap;
Expand Down Expand Up @@ -107,10 +108,26 @@ public final class PlatformDependent {
private static final boolean USE_DIRECT_BUFFER_NO_CLEANER;
private static final AtomicLong DIRECT_MEMORY_COUNTER;
private static final long DIRECT_MEMORY_LIMIT;
private static final ThreadLocalRandomProvider RANDOM_PROVIDER;

public static final boolean BIG_ENDIAN_NATIVE_ORDER = ByteOrder.nativeOrder() == ByteOrder.BIG_ENDIAN;

static {
if (javaVersion() >= 7) {
RANDOM_PROVIDER = new ThreadLocalRandomProvider() {
@Override
public Random current() {
return java.util.concurrent.ThreadLocalRandom.current();
}
};
} else {
RANDOM_PROVIDER = new ThreadLocalRandomProvider() {
@Override
public Random current() {
return ThreadLocalRandom.current();
}
};
}
if (logger.isDebugEnabled()) {
logger.debug("-Dio.netty.noPreferDirect: {}", !DIRECT_BUFFER_PREFERRED);
}
Expand Down Expand Up @@ -877,6 +894,13 @@ public static <C> Deque<C> newConcurrentDeque() {
}
}

/**
* Return a {@link Random} which is not-threadsafe and so can only be used from the same thread.
*/
public static Random threadLocalRandom() {
return RANDOM_PROVIDER.current();
}

private static boolean isAndroid0() {
boolean android;
try {
Expand Down Expand Up @@ -1382,6 +1406,10 @@ public long value() {
}
}

private interface ThreadLocalRandomProvider {
Random current();
}

private PlatformDependent() {
// only static method supported
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,13 +16,14 @@

package io.netty.handler.ssl.util;

import io.netty.util.internal.PlatformDependent;
import io.netty.util.internal.ThreadLocalRandom;

import java.security.SecureRandom;
import java.util.Random;

/**
* Insecure {@link java.security.SecureRandom} which relies on {@link ThreadLocalRandom} for random number generation.
* Insecure {@link SecureRandom} which relies on {@link ThreadLocalRandom} for random number generation.
*/
final class ThreadLocalInsecureRandom extends SecureRandom {

Expand Down Expand Up @@ -95,6 +96,6 @@ public double nextGaussian() {
}

private static Random random() {
return ThreadLocalRandom.current();
return PlatformDependent.threadLocalRandom();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@
import io.netty.handler.ssl.ApplicationProtocolConfig.SelectorFailureBehavior;
import io.netty.handler.ssl.util.InsecureTrustManagerFactory;
import io.netty.handler.ssl.util.SelfSignedCertificate;
import io.netty.util.internal.ThreadLocalRandom;
import io.netty.util.internal.PlatformDependent;
import org.junit.Assume;
import org.junit.BeforeClass;
import org.junit.Test;
Expand Down Expand Up @@ -142,7 +142,7 @@ public void testWrapBuffersNoWritePendingError() throws Exception {

ByteBuffer src = allocateBuffer(1024 * 10);
byte[] data = new byte[src.capacity()];
ThreadLocalRandom.current().nextBytes(data);
PlatformDependent.threadLocalRandom().nextBytes(data);
src.put(data).flip();
ByteBuffer dst = allocateBuffer(1);
// Try to wrap multiple times so we are more likely to hit the issue.
Expand Down
Loading

0 comments on commit fbf0e5f

Please sign in to comment.