Java 8 migration. Remove ThreadLocalProvider and inline java.util.concurrent.ThreadLocalRandom.current() where necessary. (#8762)

Motivation:

Custom Netty ThreadLocalRandom and ThreadLocalRandomProvider classes are no longer needed and can be removed.

Modification:

Remove own ThreadLocalRandom

Result:

Less code to maintain
This commit is contained in:
Dmitriy Dumanskiy 2019-01-22 21:14:28 +02:00 committed by Norman Maurer
parent 32d96a7f79
commit 7b92ff2500
34 changed files with 141 additions and 540 deletions

View File

@ -18,7 +18,6 @@ package io.netty.buffer;
import io.netty.util.ByteProcessor;
import io.netty.util.CharsetUtil;
import io.netty.util.IllegalReferenceCountException;
import io.netty.util.internal.PlatformDependent;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
@ -46,6 +45,7 @@ import java.util.Random;
import java.util.Set;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
@ -2299,7 +2299,7 @@ public abstract class AbstractByteBufTest {
int i = CAPACITY * 3 / 4 - 1;
@Override
public boolean process(byte value) throws Exception {
public boolean process(byte value) {
assertThat(value, is((byte) (i + 1)));
lastIndex.set(i);
i --;
@ -2326,7 +2326,7 @@ public abstract class AbstractByteBufTest {
assertEquals(1, buf.remaining());
byte[] data = new byte[a];
PlatformDependent.threadLocalRandom().nextBytes(data);
ThreadLocalRandom.current().nextBytes(data);
buffer.writeBytes(data);
buf = buffer.internalNioBuffer(buffer.readerIndex(), a);

View File

@ -16,7 +16,6 @@
package io.netty.buffer;
import io.netty.util.ReferenceCountUtil;
import io.netty.util.internal.PlatformDependent;
import org.junit.Assume;
import org.junit.Test;
@ -28,6 +27,7 @@ import java.util.ConcurrentModificationException;
import java.util.Iterator;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.concurrent.ThreadLocalRandom;
import static io.netty.buffer.Unpooled.EMPTY_BUFFER;
import static io.netty.buffer.Unpooled.buffer;
@ -1231,7 +1231,7 @@ public abstract class AbstractCompositeByteBufTest extends AbstractByteBufTest {
private static void testDecompose(int offset, int length, int expectedListSize) {
byte[] bytes = new byte[1024];
PlatformDependent.threadLocalRandom().nextBytes(bytes);
ThreadLocalRandom.current().nextBytes(bytes);
ByteBuf buf = wrappedBuffer(bytes);
CompositeByteBuf composite = compositeBuffer();

View File

@ -15,10 +15,10 @@
*/
package io.netty.buffer;
import io.netty.util.internal.PlatformDependent;
import org.junit.Test;
import java.nio.ByteBuffer;
import java.util.concurrent.ThreadLocalRandom;
import static org.junit.Assert.assertEquals;
@ -40,7 +40,7 @@ public class ReadOnlyByteBufferBufTest extends ReadOnlyDirectByteBufferBufTest {
private static void testCopy(boolean direct) {
byte[] bytes = new byte[1024];
PlatformDependent.threadLocalRandom().nextBytes(bytes);
ThreadLocalRandom.current().nextBytes(bytes);
ByteBuffer nioBuffer = direct ? ByteBuffer.allocateDirect(bytes.length) : ByteBuffer.allocate(bytes.length);
nioBuffer.put(bytes).flip();

View File

@ -15,7 +15,6 @@
*/
package io.netty.buffer;
import io.netty.util.internal.PlatformDependent;
import org.junit.Assert;
import org.junit.Test;
@ -27,6 +26,7 @@ import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.ReadOnlyBufferException;
import java.nio.channels.FileChannel;
import java.util.concurrent.ThreadLocalRandom;
public class ReadOnlyDirectByteBufferBufTest {
@ -295,7 +295,7 @@ public class ReadOnlyDirectByteBufferBufTest {
try {
output = new FileOutputStream(file).getChannel();
byte[] bytes = new byte[1024];
PlatformDependent.threadLocalRandom().nextBytes(bytes);
ThreadLocalRandom.current().nextBytes(bytes);
output.write(ByteBuffer.wrap(bytes));
input = new FileInputStream(file).getChannel();

View File

@ -15,12 +15,12 @@
*/
package io.netty.buffer;
import io.netty.util.internal.PlatformDependent;
import org.junit.Assume;
import org.junit.Ignore;
import org.junit.Test;
import java.nio.ByteBuffer;
import java.util.concurrent.ThreadLocalRandom;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
@ -35,7 +35,7 @@ public class SlicedByteBufTest extends AbstractByteBufTest {
@Override
protected final ByteBuf newBuffer(int length, int maxCapacity) {
Assume.assumeTrue(maxCapacity == Integer.MAX_VALUE);
int offset = length == 0 ? 0 : PlatformDependent.threadLocalRandom().nextInt(length);
int offset = length == 0 ? 0 : ThreadLocalRandom.current().nextInt(length);
ByteBuf buffer = Unpooled.buffer(length * 2);
ByteBuf slice = newSlice(buffer, offset, length);
assertEquals(0, slice.readerIndex());

View File

@ -18,12 +18,12 @@ package io.netty.handler.codec.dns;
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 org.junit.Test;
import java.net.InetAddress;
import java.util.concurrent.ThreadLocalRandom;
import static org.junit.Assert.assertEquals;
@ -146,6 +146,6 @@ public class DefaultDnsRecordEncoderTest {
}
private static int nextInt(int max) {
return PlatformDependent.threadLocalRandom().nextInt(max);
return ThreadLocalRandom.current().nextInt(max);
}
}

View File

@ -34,7 +34,6 @@ import io.netty.handler.codec.http.HttpUtil;
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 java.io.File;
@ -46,6 +45,7 @@ import java.util.ArrayList;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;
import java.util.concurrent.ThreadLocalRandom;
import java.util.regex.Pattern;
import static io.netty.buffer.Unpooled.wrappedBuffer;
@ -289,7 +289,7 @@ public class HttpPostRequestEncoder implements ChunkedInput<HttpContent> {
*/
private static String getNewMultipartDelimiter() {
// construct a generated delimiter
return Long.toHexString(PlatformDependent.threadLocalRandom().nextLong());
return Long.toHexString(ThreadLocalRandom.current().nextLong());
}
/**

View File

@ -20,10 +20,10 @@ import io.netty.buffer.Unpooled;
import io.netty.handler.codec.base64.Base64;
import io.netty.util.CharsetUtil;
import io.netty.util.concurrent.FastThreadLocal;
import io.netty.util.internal.PlatformDependent;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.concurrent.ThreadLocalRandom;
/**
* A utility class mainly for use by web sockets
@ -106,7 +106,7 @@ final class WebSocketUtil {
*/
static byte[] randomBytes(int size) {
byte[] bytes = new byte[size];
PlatformDependent.threadLocalRandom().nextBytes(bytes);
ThreadLocalRandom.current().nextBytes(bytes);
return bytes;
}
@ -119,7 +119,7 @@ final class WebSocketUtil {
*/
static int randomNumber(int minimum, int maximum) {
assert minimum < maximum;
double fraction = PlatformDependent.threadLocalRandom().nextDouble();
double fraction = ThreadLocalRandom.current().nextDouble();
// the idea here is that nextDouble gives us a random value
//

View File

@ -23,12 +23,12 @@ import io.netty.buffer.UnpooledHeapByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.embedded.EmbeddedChannel;
import io.netty.util.internal.PlatformDependent;
import org.junit.Test;
import java.util.List;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadLocalRandom;
import static org.junit.Assert.*;
@ -40,7 +40,7 @@ public class ByteToMessageDecoderTest {
private boolean removed;
@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) {
assertFalse(removed);
in.readByte();
ctx.pipeline().remove(this);
@ -63,7 +63,7 @@ public class ByteToMessageDecoderTest {
private boolean removed;
@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) {
assertFalse(removed);
in.readByte();
ctx.pipeline().remove(this);
@ -116,7 +116,7 @@ public class ByteToMessageDecoderTest {
private EmbeddedChannel newInternalBufferTestChannel() {
return new EmbeddedChannel(new ByteToMessageDecoder() {
@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) {
ByteBuf byteBuf = internalBuffer();
assertEquals(1, byteBuf.refCnt());
in.readByte();
@ -125,7 +125,7 @@ public class ByteToMessageDecoderTest {
}
@Override
protected void handlerRemoved0(ChannelHandlerContext ctx) throws Exception {
protected void handlerRemoved0(ChannelHandlerContext ctx) {
assertCumulationReleased(internalBuffer());
}
});
@ -135,18 +135,18 @@ public class ByteToMessageDecoderTest {
public void handlerRemovedWillNotReleaseBufferIfDecodeInProgress() {
EmbeddedChannel channel = new EmbeddedChannel(new ByteToMessageDecoder() {
@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) {
ctx.pipeline().remove(this);
assertTrue(in.refCnt() != 0);
}
@Override
protected void handlerRemoved0(ChannelHandlerContext ctx) throws Exception {
protected void handlerRemoved0(ChannelHandlerContext ctx) {
assertCumulationReleased(internalBuffer());
}
});
byte[] bytes = new byte[1024];
PlatformDependent.threadLocalRandom().nextBytes(bytes);
ThreadLocalRandom.current().nextBytes(bytes);
assertTrue(channel.writeInbound(Unpooled.wrappedBuffer(bytes)));
assertTrue(channel.finishAndReleaseAll());
@ -163,30 +163,30 @@ public class ByteToMessageDecoderTest {
final ByteBuf buf = Unpooled.buffer().writeBytes(new byte[] {'a', 'b'});
EmbeddedChannel channel = new EmbeddedChannel(new ByteToMessageDecoder() {
@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) {
int readable = in.readableBytes();
assertTrue(readable > 0);
in.skipBytes(readable);
}
@Override
protected void decodeLast(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
protected void decodeLast(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) {
assertFalse(in.isReadable());
out.add("data");
}
}, new ChannelInboundHandlerAdapter() {
@Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
public void channelInactive(ChannelHandlerContext ctx) {
queue.add(3);
}
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
public void channelRead(ChannelHandlerContext ctx, Object msg) {
queue.add(1);
}
@Override
public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
public void channelReadComplete(ChannelHandlerContext ctx) {
if (!ctx.channel().isActive()) {
queue.add(2);
}
@ -206,7 +206,7 @@ public class ByteToMessageDecoderTest {
final Object upgradeMessage = new Object();
final ByteToMessageDecoder decoder = new ByteToMessageDecoder() {
@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) {
assertEquals('a', in.readByte());
out.add(upgradeMessage);
}
@ -214,7 +214,7 @@ public class ByteToMessageDecoderTest {
EmbeddedChannel channel = new EmbeddedChannel(decoder, new ChannelInboundHandlerAdapter() {
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
public void channelRead(ChannelHandlerContext ctx, Object msg) {
if (msg == upgradeMessage) {
ctx.pipeline().remove(decoder);
return;
@ -236,17 +236,17 @@ public class ByteToMessageDecoderTest {
public void testDecodeLastEmptyBuffer() {
EmbeddedChannel channel = new EmbeddedChannel(new ByteToMessageDecoder() {
@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) {
int readable = in.readableBytes();
assertTrue(readable > 0);
out.add(in.readBytes(readable));
}
});
byte[] bytes = new byte[1024];
PlatformDependent.threadLocalRandom().nextBytes(bytes);
ThreadLocalRandom.current().nextBytes(bytes);
assertTrue(channel.writeInbound(Unpooled.wrappedBuffer(bytes)));
assertBuffer(Unpooled.wrappedBuffer(bytes), (ByteBuf) channel.readInbound());
assertBuffer(Unpooled.wrappedBuffer(bytes), channel.readInbound());
assertNull(channel.readInbound());
assertFalse(channel.finish());
assertNull(channel.readInbound());
@ -258,7 +258,7 @@ public class ByteToMessageDecoderTest {
private boolean decodeLast;
@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) {
int readable = in.readableBytes();
assertTrue(readable > 0);
if (!decodeLast && readable == 1) {
@ -275,13 +275,13 @@ public class ByteToMessageDecoderTest {
}
});
byte[] bytes = new byte[1024];
PlatformDependent.threadLocalRandom().nextBytes(bytes);
ThreadLocalRandom.current().nextBytes(bytes);
assertTrue(channel.writeInbound(Unpooled.wrappedBuffer(bytes)));
assertBuffer(Unpooled.wrappedBuffer(bytes, 0, bytes.length - 1), (ByteBuf) channel.readInbound());
assertBuffer(Unpooled.wrappedBuffer(bytes, 0, bytes.length - 1), channel.readInbound());
assertNull(channel.readInbound());
assertTrue(channel.finish());
assertBuffer(Unpooled.wrappedBuffer(bytes, bytes.length - 1, 1), (ByteBuf) channel.readInbound());
assertBuffer(Unpooled.wrappedBuffer(bytes, bytes.length - 1, 1), channel.readInbound());
assertNull(channel.readInbound());
}
@ -298,7 +298,7 @@ public class ByteToMessageDecoderTest {
public void testReadOnlyBuffer() {
EmbeddedChannel channel = new EmbeddedChannel(new ByteToMessageDecoder() {
@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) {
}
});
assertFalse(channel.writeInbound(Unpooled.buffer(8).writeByte(1).asReadOnly()));

View File

@ -21,12 +21,12 @@ import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.embedded.EmbeddedChannel;
import io.netty.channel.socket.ChannelInputShutdownEvent;
import io.netty.util.internal.PlatformDependent;
import org.junit.Test;
import java.util.List;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.atomic.AtomicReference;
import static org.junit.Assert.*;
@ -303,7 +303,7 @@ public class ReplayingDecoderTest {
}
});
byte[] bytes = new byte[1024];
PlatformDependent.threadLocalRandom().nextBytes(bytes);
ThreadLocalRandom.current().nextBytes(bytes);
assertTrue(channel.writeInbound(Unpooled.wrappedBuffer(bytes)));
assertTrue(channel.finishAndReleaseAll());

View File

@ -19,7 +19,6 @@ import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufUtil;
import io.netty.buffer.Unpooled;
import io.netty.util.CharsetUtil;
import io.netty.util.internal.PlatformDependent;
import io.netty.util.internal.StringUtil;
import org.junit.Test;
@ -27,6 +26,7 @@ import java.io.ByteArrayInputStream;
import java.nio.ByteOrder;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.util.concurrent.ThreadLocalRandom;
import static io.netty.buffer.Unpooled.copiedBuffer;
import static org.junit.Assert.assertEquals;
@ -142,7 +142,7 @@ public class Base64Test {
private static void testEncodeDecode(int size, ByteOrder order) {
byte[] bytes = new byte[size];
PlatformDependent.threadLocalRandom().nextBytes(bytes);
ThreadLocalRandom.current().nextBytes(bytes);
ByteBuf src = Unpooled.wrappedBuffer(bytes).order(order);
ByteBuf encoded = Base64.encode(src);

View File

@ -22,13 +22,13 @@ import io.netty.channel.embedded.EmbeddedChannel;
import io.netty.util.CharsetUtil;
import io.netty.util.ReferenceCountUtil;
import io.netty.util.internal.EmptyArrays;
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.concurrent.ThreadLocalRandom;
import java.util.zip.DeflaterOutputStream;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
@ -83,7 +83,7 @@ public abstract class ZlibTest {
"</body></html>").getBytes(CharsetUtil.UTF_8);
static {
Random rand = PlatformDependent.threadLocalRandom();
Random rand = ThreadLocalRandom.current();
rand.nextBytes(BYTES_SMALL);
rand.nextBytes(BYTES_LARGE);
}

View File

@ -17,19 +17,19 @@
package io.netty.util;
import io.netty.util.internal.EmptyArrays;
import io.netty.util.internal.PlatformDependent;
import io.netty.util.internal.SystemPropertyUtil;
import io.netty.util.internal.logging.InternalLogger;
import io.netty.util.internal.logging.InternalLoggerFactory;
import java.lang.ref.WeakReference;
import java.lang.ref.ReferenceQueue;
import java.lang.ref.WeakReference;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.atomic.AtomicIntegerFieldUpdater;
import java.util.concurrent.atomic.AtomicReference;
import java.util.concurrent.atomic.AtomicReferenceFieldUpdater;
@ -257,7 +257,7 @@ public class ResourceLeakDetector<T> {
}
if (level.ordinal() < Level.PARANOID.ordinal()) {
if ((PlatformDependent.threadLocalRandom().nextInt(samplingInterval)) == 0) {
if (ThreadLocalRandom.current().nextInt(samplingInterval) == 0) {
reportLeak();
return new DefaultResourceLeak(obj, refQueue, allLeaks);
}
@ -429,7 +429,7 @@ public class ResourceLeakDetector<T> {
final int numElements = oldHead.pos + 1;
if (numElements >= TARGET_RECORDS) {
final int backOffFactor = Math.min(numElements - TARGET_RECORDS, 30);
if (dropped = PlatformDependent.threadLocalRandom().nextInt(1 << backOffFactor) != 0) {
if (dropped = ThreadLocalRandom.current().nextInt(1 << backOffFactor) != 0) {
prevHead = oldHead.next;
}
} else {

View File

@ -30,6 +30,7 @@ import java.util.BitSet;
import java.util.IdentityHashMap;
import java.util.Map;
import java.util.WeakHashMap;
import java.util.concurrent.ThreadLocalRandom;
/**
* The internal data structure that stores the thread-local variables for Netty and all {@link FastThreadLocal}s.
@ -233,7 +234,7 @@ public final class InternalThreadLocalMap extends UnpaddedInternalThreadLocalMap
public ThreadLocalRandom random() {
ThreadLocalRandom r = random;
if (r == null) {
random = r = new ThreadLocalRandom();
random = r = ThreadLocalRandom.current();
}
return r;
}

View File

@ -28,6 +28,7 @@ import java.util.Enumeration;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.ThreadLocalRandom;
import static io.netty.util.internal.EmptyArrays.EMPTY_BYTES;
@ -138,7 +139,7 @@ public final class MacAddressUtil {
byte[] bestMacAddr = bestAvailableMac();
if (bestMacAddr == null) {
bestMacAddr = new byte[EUI64_MAC_ADDRESS_LENGTH];
PlatformDependent.threadLocalRandom().nextBytes(bestMacAddr);
ThreadLocalRandom.current().nextBytes(bestMacAddr);
logger.warn(
"Failed to find a usable hardware address from the network interfaces; using random bytes: {}",
formatAddress(bestMacAddr));

View File

@ -35,7 +35,9 @@ import java.util.ArrayList;
import java.util.Arrays;
import java.util.EnumSet;
import java.util.List;
import java.util.Random;
import java.util.Set;
import java.util.concurrent.ThreadLocalRandom;
/**
* Helper class to load JNI resources.
@ -279,8 +281,7 @@ public final class NativeLibraryLoader {
// We found our ID... now monkey-patch it!
for (int i = 0; i < nameBytes.length; i++) {
// We should only use bytes as replacement that are in our UNIQUE_ID_BYTES array.
bytes[idIdx + i] = UNIQUE_ID_BYTES[PlatformDependent.threadLocalRandom()
.nextInt(UNIQUE_ID_BYTES.length)];
bytes[idIdx + i] = UNIQUE_ID_BYTES[ThreadLocalRandom.current().nextInt(UNIQUE_ID_BYTES.length)];
}
if (logger.isDebugEnabled()) {

View File

@ -38,12 +38,8 @@ import java.security.PrivilegedAction;
import java.util.Deque;
import java.util.List;
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;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.atomic.AtomicLong;
import java.util.regex.Matcher;
@ -99,7 +95,6 @@ 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;
private static final Cleaner CLEANER;
private static final int UNINITIALIZED_ARRAY_ALLOCATION_THRESHOLD;
@ -113,22 +108,6 @@ public final class PlatformDependent {
};
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();
}
};
}
// Here is how the system property is used:
//
// * < 0 - Don't use cleaner, and inherit max direct memory from java. In this case the
@ -895,13 +874,6 @@ public final class PlatformDependent {
}
}
/**
* 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 isWindows0() {
boolean windows = SystemPropertyUtil.get("os.name", "").toLowerCase(Locale.US).contains("win");
if (windows) {
@ -1309,10 +1281,6 @@ public final class PlatformDependent {
return "unknown";
}
private interface ThreadLocalRandomProvider {
Random current();
}
private PlatformDependent() {
// only static method supported
}

View File

@ -1,386 +0,0 @@
/*
* Copyright 2014 The Netty Project
*
* The Netty Project licenses this file to you under the Apache License,
* version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
/*
* Written by Doug Lea with assistance from members of JCP JSR-166
* Expert Group and released to the public domain, as explained at
* http://creativecommons.org/publicdomain/zero/1.0/
*/
package io.netty.util.internal;
import io.netty.util.internal.logging.InternalLogger;
import io.netty.util.internal.logging.InternalLoggerFactory;
import java.lang.Thread.UncaughtExceptionHandler;
import java.security.SecureRandom;
import java.util.Random;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;
/**
* A random number generator isolated to the current thread. Like the
* global {@link java.util.Random} generator used by the {@link
* java.lang.Math} class, a {@code ThreadLocalRandom} is initialized
* with an internally generated seed that may not otherwise be
* modified. When applicable, use of {@code ThreadLocalRandom} rather
* than shared {@code Random} objects in concurrent programs will
* typically encounter much less overhead and contention. Use of
* {@code ThreadLocalRandom} is particularly appropriate when multiple
* tasks (for example, each a {@link io.netty.util.internal.chmv8.ForkJoinTask}) use random numbers
* in parallel in thread pools.
*
* <p>Usages of this class should typically be of the form:
* {@code ThreadLocalRandom.current().nextX(...)} (where
* {@code X} is {@code Int}, {@code Long}, etc).
* When all usages are of this form, it is never possible to
* accidently share a {@code ThreadLocalRandom} across multiple threads.
*
* <p>This class also provides additional commonly used bounded random
* generation methods.
*
* //since 1.7
* //author Doug Lea
*/
@SuppressWarnings("all")
public final class ThreadLocalRandom extends Random {
private static final InternalLogger logger = InternalLoggerFactory.getInstance(ThreadLocalRandom.class);
private static final AtomicLong seedUniquifier = new AtomicLong();
private static volatile long initialSeedUniquifier;
private static final Thread seedGeneratorThread;
private static final BlockingQueue<Long> seedQueue;
private static final long seedGeneratorStartTime;
private static volatile long seedGeneratorEndTime;
static {
initialSeedUniquifier = SystemPropertyUtil.getLong("io.netty.initialSeedUniquifier", 0);
if (initialSeedUniquifier == 0) {
boolean secureRandom = SystemPropertyUtil.getBoolean("java.util.secureRandomSeed", false);
if (secureRandom) {
seedQueue = new LinkedBlockingQueue<Long>();
seedGeneratorStartTime = System.nanoTime();
// Try to generate a real random number from /dev/random.
// Get from a different thread to avoid blocking indefinitely on a machine without much entropy.
seedGeneratorThread = new Thread("initialSeedUniquifierGenerator") {
@Override
public void run() {
final SecureRandom random = new SecureRandom(); // Get the real random seed from /dev/random
final byte[] seed = random.generateSeed(8);
seedGeneratorEndTime = System.nanoTime();
long s = ((long) seed[0] & 0xff) << 56 |
((long) seed[1] & 0xff) << 48 |
((long) seed[2] & 0xff) << 40 |
((long) seed[3] & 0xff) << 32 |
((long) seed[4] & 0xff) << 24 |
((long) seed[5] & 0xff) << 16 |
((long) seed[6] & 0xff) << 8 |
(long) seed[7] & 0xff;
seedQueue.add(s);
}
};
seedGeneratorThread.setDaemon(true);
seedGeneratorThread.setUncaughtExceptionHandler(new UncaughtExceptionHandler() {
@Override
public void uncaughtException(Thread t, Throwable e) {
logger.debug("An exception has been raised by {}", t.getName(), e);
}
});
seedGeneratorThread.start();
} else {
initialSeedUniquifier = mix64(System.currentTimeMillis()) ^ mix64(System.nanoTime());
seedGeneratorThread = null;
seedQueue = null;
seedGeneratorStartTime = 0L;
}
} else {
seedGeneratorThread = null;
seedQueue = null;
seedGeneratorStartTime = 0L;
}
}
public static void setInitialSeedUniquifier(long initialSeedUniquifier) {
ThreadLocalRandom.initialSeedUniquifier = initialSeedUniquifier;
}
public static long getInitialSeedUniquifier() {
// Use the value set via the setter.
long initialSeedUniquifier = ThreadLocalRandom.initialSeedUniquifier;
if (initialSeedUniquifier != 0) {
return initialSeedUniquifier;
}
synchronized (ThreadLocalRandom.class) {
initialSeedUniquifier = ThreadLocalRandom.initialSeedUniquifier;
if (initialSeedUniquifier != 0) {
return initialSeedUniquifier;
}
// Get the random seed from the generator thread with timeout.
final long timeoutSeconds = 3;
final long deadLine = seedGeneratorStartTime + TimeUnit.SECONDS.toNanos(timeoutSeconds);
boolean interrupted = false;
for (;;) {
final long waitTime = deadLine - System.nanoTime();
try {
final Long seed;
if (waitTime <= 0) {
seed = seedQueue.poll();
} else {
seed = seedQueue.poll(waitTime, TimeUnit.NANOSECONDS);
}
if (seed != null) {
initialSeedUniquifier = seed;
break;
}
} catch (InterruptedException e) {
interrupted = true;
logger.warn("Failed to generate a seed from SecureRandom due to an InterruptedException.");
break;
}
if (waitTime <= 0) {
seedGeneratorThread.interrupt();
logger.warn(
"Failed to generate a seed from SecureRandom within {} seconds. " +
"Not enough entropy?", timeoutSeconds
);
break;
}
}
// Just in case the initialSeedUniquifier is zero or some other constant
initialSeedUniquifier ^= 0x3255ecdc33bae119L; // just a meaningless random number
initialSeedUniquifier ^= Long.reverse(System.nanoTime());
ThreadLocalRandom.initialSeedUniquifier = initialSeedUniquifier;
if (interrupted) {
// Restore the interrupt status because we don't know how to/don't need to handle it here.
Thread.currentThread().interrupt();
// Interrupt the generator thread if it's still running,
// in the hope that the SecureRandom provider raises an exception on interruption.
seedGeneratorThread.interrupt();
}
if (seedGeneratorEndTime == 0) {
seedGeneratorEndTime = System.nanoTime();
}
return initialSeedUniquifier;
}
}
private static long newSeed() {
for (;;) {
final long current = seedUniquifier.get();
final long actualCurrent = current != 0? current : getInitialSeedUniquifier();
// L'Ecuyer, "Tables of Linear Congruential Generators of Different Sizes and Good Lattice Structure", 1999
final long next = actualCurrent * 181783497276652981L;
if (seedUniquifier.compareAndSet(current, next)) {
if (current == 0 && logger.isDebugEnabled()) {
if (seedGeneratorEndTime != 0) {
logger.debug(String.format(
"-Dio.netty.initialSeedUniquifier: 0x%016x (took %d ms)",
actualCurrent,
TimeUnit.NANOSECONDS.toMillis(seedGeneratorEndTime - seedGeneratorStartTime)));
} else {
logger.debug(String.format("-Dio.netty.initialSeedUniquifier: 0x%016x", actualCurrent));
}
}
return next ^ System.nanoTime();
}
}
}
// Borrowed from
// http://gee.cs.oswego.edu/cgi-bin/viewcvs.cgi/jsr166/src/main/java/util/concurrent/ThreadLocalRandom.java
private static long mix64(long z) {
z = (z ^ (z >>> 33)) * 0xff51afd7ed558ccdL;
z = (z ^ (z >>> 33)) * 0xc4ceb9fe1a85ec53L;
return z ^ (z >>> 33);
}
// same constants as Random, but must be redeclared because private
private static final long multiplier = 0x5DEECE66DL;
private static final long addend = 0xBL;
private static final long mask = (1L << 48) - 1;
/**
* The random seed. We can't use super.seed.
*/
private long rnd;
/**
* Initialization flag to permit calls to setSeed to succeed only
* while executing the Random constructor. We can't allow others
* since it would cause setting seed in one part of a program to
* unintentionally impact other usages by the thread.
*/
boolean initialized;
// Padding to help avoid memory contention among seed updates in
// different TLRs in the common case that they are located near
// each other.
private long pad0, pad1, pad2, pad3, pad4, pad5, pad6, pad7;
/**
* Constructor called only by localRandom.initialValue.
*/
ThreadLocalRandom() {
super(newSeed());
initialized = true;
}
/**
* Returns the current thread's {@code ThreadLocalRandom}.
*
* @return the current thread's {@code ThreadLocalRandom}
*/
public static ThreadLocalRandom current() {
return InternalThreadLocalMap.get().random();
}
/**
* Throws {@code UnsupportedOperationException}. Setting seeds in
* this generator is not supported.
*
* @throws UnsupportedOperationException always
*/
public void setSeed(long seed) {
if (initialized) {
throw new UnsupportedOperationException();
}
rnd = (seed ^ multiplier) & mask;
}
protected int next(int bits) {
rnd = (rnd * multiplier + addend) & mask;
return (int) (rnd >>> (48 - bits));
}
/**
* Returns a pseudorandom, uniformly distributed value between the
* given least value (inclusive) and bound (exclusive).
*
* @param least the least value returned
* @param bound the upper bound (exclusive)
* @throws IllegalArgumentException if least greater than or equal
* to bound
* @return the next value
*/
public int nextInt(int least, int bound) {
if (least >= bound) {
throw new IllegalArgumentException();
}
return nextInt(bound - least) + least;
}
/**
* Returns a pseudorandom, uniformly distributed value
* between 0 (inclusive) and the specified value (exclusive).
*
* @param n the bound on the random number to be returned. Must be
* positive.
* @return the next value
* @throws IllegalArgumentException if n is not positive
*/
public long nextLong(long n) {
if (n <= 0) {
throw new IllegalArgumentException("n must be positive");
}
// Divide n by two until small enough for nextInt. On each
// iteration (at most 31 of them but usually much less),
// randomly choose both whether to include high bit in result
// (offset) and whether to continue with the lower vs upper
// half (which makes a difference only if odd).
long offset = 0;
while (n >= Integer.MAX_VALUE) {
int bits = next(2);
long half = n >>> 1;
long nextn = ((bits & 2) == 0) ? half : n - half;
if ((bits & 1) == 0) {
offset += n - nextn;
}
n = nextn;
}
return offset + nextInt((int) n);
}
/**
* Returns a pseudorandom, uniformly distributed value between the
* given least value (inclusive) and bound (exclusive).
*
* @param least the least value returned
* @param bound the upper bound (exclusive)
* @return the next value
* @throws IllegalArgumentException if least greater than or equal
* to bound
*/
public long nextLong(long least, long bound) {
if (least >= bound) {
throw new IllegalArgumentException();
}
return nextLong(bound - least) + least;
}
/**
* Returns a pseudorandom, uniformly distributed {@code double} value
* between 0 (inclusive) and the specified value (exclusive).
*
* @param n the bound on the random number to be returned. Must be
* positive.
* @return the next value
* @throws IllegalArgumentException if n is not positive
*/
public double nextDouble(double n) {
if (n <= 0) {
throw new IllegalArgumentException("n must be positive");
}
return nextDouble() * n;
}
/**
* Returns a pseudorandom, uniformly distributed value between the
* given least value (inclusive) and bound (exclusive).
*
* @param least the least value returned
* @param bound the upper bound (exclusive)
* @return the next value
* @throws IllegalArgumentException if least greater than or equal
* to bound
*/
public double nextDouble(double least, double bound) {
if (least >= bound) {
throw new IllegalArgumentException();
}
return nextDouble() * (bound - least) + least;
}
private static final long serialVersionUID = -5851777807851030925L;
}

View File

@ -23,6 +23,7 @@ import java.nio.charset.CharsetDecoder;
import java.nio.charset.CharsetEncoder;
import java.util.ArrayList;
import java.util.Map;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.atomic.AtomicInteger;
/**

View File

@ -15,7 +15,6 @@
*/
package io.netty.util;
import io.netty.util.internal.ThreadLocalRandom;
import org.junit.Test;
import java.util.ArrayDeque;
@ -24,6 +23,7 @@ import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.atomic.AtomicInteger;
import static org.junit.Assert.assertEquals;

View File

@ -17,7 +17,7 @@ package io.netty.util.internal;
import org.junit.Test;
import static org.junit.Assert.*;
import static org.junit.Assert.assertTrue;
public class ThreadLocalRandomTest {
@ -27,7 +27,6 @@ public class ThreadLocalRandomTest {
Thread.currentThread().interrupt();
assertTrue("Assert that thread is interrupted before invocation of getInitialSeedUniquifier()",
Thread.currentThread().isInterrupted());
ThreadLocalRandom.getInitialSeedUniquifier();
assertTrue("Assert that thread is interrupted after invocation of getInitialSeedUniquifier()",
Thread.currentThread().isInterrupted());
} finally {

View File

@ -16,13 +16,12 @@
package io.netty.handler.ssl.util;
import io.netty.util.internal.PlatformDependent;
import java.security.SecureRandom;
import java.util.Random;
import java.util.concurrent.ThreadLocalRandom;
/**
* Insecure {@link SecureRandom} which relies on {@link PlatformDependent#threadLocalRandom()} for random number
* Insecure {@link SecureRandom} which relies on {@link ThreadLocalRandom#current()} for random number
* generation.
*/
final class ThreadLocalInsecureRandom extends SecureRandom {
@ -96,6 +95,6 @@ final class ThreadLocalInsecureRandom extends SecureRandom {
}
private static Random random() {
return PlatformDependent.threadLocalRandom();
return ThreadLocalRandom.current();
}
}

View File

@ -40,6 +40,7 @@ import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ThreadLocalRandom;
import javax.net.ssl.SSLEngine;
import javax.net.ssl.SSLEngineResult;
import javax.net.ssl.SSLException;
@ -244,7 +245,7 @@ public class OpenSslEngineTest extends SSLEngineTest {
ByteBuffer src = allocateBuffer(1024 * 10);
byte[] data = new byte[src.capacity()];
PlatformDependent.threadLocalRandom().nextBytes(data);
ThreadLocalRandom.current().nextBytes(data);
src.put(data).flip();
ByteBuffer dst = allocateBuffer(1);
// Try to wrap multiple times so we are more likely to hit the issue.

View File

@ -39,11 +39,11 @@ import io.netty.handler.ssl.util.SelfSignedCertificate;
import io.netty.util.CharsetUtil;
import io.netty.util.NetUtil;
import io.netty.util.ReferenceCountUtil;
import io.netty.util.internal.ResourcesUtil;
import io.netty.util.concurrent.Future;
import io.netty.util.concurrent.Promise;
import io.netty.util.internal.EmptyArrays;
import io.netty.util.internal.PlatformDependent;
import io.netty.util.internal.ResourcesUtil;
import io.netty.util.internal.StringUtil;
import org.junit.After;
import org.junit.Assume;
@ -53,28 +53,6 @@ import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ClosedChannelException;
import java.security.KeyStore;
import java.security.Principal;
import java.security.Provider;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.ManagerFactoryParameters;
import javax.net.ssl.SNIHostName;
@ -94,8 +72,38 @@ import javax.net.ssl.TrustManagerFactory;
import javax.net.ssl.TrustManagerFactorySpi;
import javax.net.ssl.X509TrustManager;
import javax.security.cert.X509Certificate;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ClosedChannelException;
import java.security.KeyStore;
import java.security.Principal;
import java.security.Provider;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Random;
import java.util.Set;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;
import static io.netty.handler.ssl.SslUtils.*;
import static io.netty.handler.ssl.SslUtils.PROTOCOL_SSL_V2;
import static io.netty.handler.ssl.SslUtils.PROTOCOL_SSL_V2_HELLO;
import static io.netty.handler.ssl.SslUtils.PROTOCOL_SSL_V3;
import static io.netty.handler.ssl.SslUtils.PROTOCOL_TLS_V1;
import static io.netty.handler.ssl.SslUtils.PROTOCOL_TLS_V1_1;
import static io.netty.handler.ssl.SslUtils.PROTOCOL_TLS_V1_2;
import static io.netty.handler.ssl.SslUtils.PROTOCOL_TLS_V1_3;
import static io.netty.handler.ssl.SslUtils.SSL_RECORD_HEADER_LENGTH;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
@ -265,7 +273,7 @@ public abstract class SSLEngineTest {
case Heap:
return ByteBuffer.allocate(len);
case Mixed:
return PlatformDependent.threadLocalRandom().nextBoolean() ?
return ThreadLocalRandom.current().nextBoolean() ?
ByteBuffer.allocateDirect(len) : ByteBuffer.allocate(len);
default:
throw new Error();
@ -290,7 +298,7 @@ public abstract class SSLEngineTest {
case Heap:
return allocator.heapBuffer();
case Mixed:
return PlatformDependent.threadLocalRandom().nextBoolean() ?
return ThreadLocalRandom.current().nextBoolean() ?
allocator.directBuffer() : allocator.heapBuffer();
default:
throw new Error();
@ -305,7 +313,7 @@ public abstract class SSLEngineTest {
case Heap:
return allocator.heapBuffer(initialCapacity);
case Mixed:
return PlatformDependent.threadLocalRandom().nextBoolean() ?
return ThreadLocalRandom.current().nextBoolean() ?
allocator.directBuffer(initialCapacity) : allocator.heapBuffer(initialCapacity);
default:
throw new Error();
@ -320,7 +328,7 @@ public abstract class SSLEngineTest {
case Heap:
return allocator.heapBuffer(initialCapacity, maxCapacity);
case Mixed:
return PlatformDependent.threadLocalRandom().nextBoolean() ?
return ThreadLocalRandom.current().nextBoolean() ?
allocator.directBuffer(initialCapacity, maxCapacity) :
allocator.heapBuffer(initialCapacity, maxCapacity);
default:
@ -381,7 +389,7 @@ public abstract class SSLEngineTest {
case Heap:
return allocator.compositeHeapBuffer();
case Mixed:
return PlatformDependent.threadLocalRandom().nextBoolean() ?
return ((Random) ThreadLocalRandom.current()).nextBoolean() ?
allocator.compositeDirectBuffer() :
allocator.compositeHeapBuffer();
default:
@ -397,7 +405,7 @@ public abstract class SSLEngineTest {
case Heap:
return allocator.compositeHeapBuffer(maxNumComponents);
case Mixed:
return PlatformDependent.threadLocalRandom().nextBoolean() ?
return ((Random) ThreadLocalRandom.current()).nextBoolean() ?
allocator.compositeDirectBuffer(maxNumComponents) :
allocator.compositeHeapBuffer(maxNumComponents);
default:

View File

@ -17,13 +17,13 @@ package io.netty.microbench.handler.ssl;
import io.netty.buffer.ByteBufAllocator;
import io.netty.buffer.PooledByteBufAllocator;
import io.netty.util.internal.PlatformDependent;
import org.openjdk.jmh.annotations.Level;
import org.openjdk.jmh.annotations.Param;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.TearDown;
import java.nio.ByteBuffer;
import java.util.concurrent.ThreadLocalRandom;
import javax.net.ssl.SSLEngineResult;
import javax.net.ssl.SSLException;
@ -45,7 +45,7 @@ public abstract class AbstractSslEngineThroughputBenchmark extends AbstractSslEn
wrapSrcBuffer = allocateBuffer(messageSize);
byte[] bytes = new byte[messageSize];
PlatformDependent.threadLocalRandom().nextBytes(bytes);
ThreadLocalRandom.current().nextBytes(bytes);
wrapSrcBuffer.put(bytes);
wrapSrcBuffer.flip();

View File

@ -18,12 +18,13 @@ import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufAllocator;
import io.netty.buffer.PooledByteBufAllocator;
import io.netty.channel.embedded.EmbeddedChannel;
import io.netty.util.internal.PlatformDependent;
import org.openjdk.jmh.annotations.Level;
import org.openjdk.jmh.annotations.Param;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.TearDown;
import java.util.concurrent.ThreadLocalRandom;
public abstract class AbstractSslHandlerThroughputBenchmark extends AbstractSslHandlerBenchmark {
@Param({ "64", "128", "512", "1024", "4096" })
public int messageSize;
@ -61,7 +62,7 @@ public abstract class AbstractSslHandlerThroughputBenchmark extends AbstractSslH
wrapSrcBuffer = allocateBuffer(messageSize);
byte[] bytes = new byte[messageSize];
PlatformDependent.threadLocalRandom().nextBytes(bytes);
ThreadLocalRandom.current().nextBytes(bytes);
wrapSrcBuffer.writeBytes(bytes);
// Complete the initial TLS handshake.

View File

@ -19,7 +19,6 @@ package io.netty.resolver.dns;
import io.netty.util.NetUtil;
import io.netty.util.collection.IntObjectHashMap;
import io.netty.util.collection.IntObjectMap;
import io.netty.util.internal.PlatformDependent;
import java.net.Inet4Address;
import java.net.Inet6Address;
@ -28,6 +27,7 @@ import java.net.InetSocketAddress;
import java.net.UnknownHostException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ThreadLocalRandom;
final class DnsQueryContextManager {
@ -35,13 +35,12 @@ final class DnsQueryContextManager {
* A map whose key is the DNS server address and value is the map of the DNS query ID and its corresponding
* {@link DnsQueryContext}.
*/
final Map<InetSocketAddress, IntObjectMap<DnsQueryContext>> map =
new HashMap<InetSocketAddress, IntObjectMap<DnsQueryContext>>();
final Map<InetSocketAddress, IntObjectMap<DnsQueryContext>> map = new HashMap<>();
int add(DnsQueryContext qCtx) {
final IntObjectMap<DnsQueryContext> contexts = getOrCreateContextMap(qCtx.nameServerAddr());
int id = PlatformDependent.threadLocalRandom().nextInt(65536 - 1) + 1;
int id = ThreadLocalRandom.current().nextInt(65536 - 1) + 1;
final int maxTries = 65535 << 1;
int tries = 0;

View File

@ -16,12 +16,10 @@
package io.netty.resolver.dns;
import io.netty.util.internal.PlatformDependent;
import java.net.InetSocketAddress;
import java.util.Collections;
import java.util.List;
import java.util.Random;
import java.util.concurrent.ThreadLocalRandom;
final class ShuffledDnsServerAddressStream implements DnsServerAddressStream {
@ -45,7 +43,7 @@ final class ShuffledDnsServerAddressStream implements DnsServerAddressStream {
}
private void shuffle() {
Collections.shuffle(addresses, PlatformDependent.threadLocalRandom());
Collections.shuffle(addresses, ThreadLocalRandom.current());
}
@Override

View File

@ -86,6 +86,7 @@ import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
@ -96,12 +97,19 @@ import static io.netty.handler.codec.dns.DnsRecordType.AAAA;
import static io.netty.handler.codec.dns.DnsRecordType.CNAME;
import static io.netty.resolver.dns.DnsServerAddresses.sequential;
import static java.util.Collections.singletonList;
import static java.util.Collections.singletonMap;
import static org.hamcrest.Matchers.greaterThan;
import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.instanceOf;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.*;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
public class DnsNameResolverTest {
@ -410,7 +418,7 @@ public class DnsNameResolverTest {
if (EXCLUSIONS_RESOLVE_A.contains(name)) {
continue;
}
if (PlatformDependent.threadLocalRandom().nextBoolean()) {
if (ThreadLocalRandom.current().nextBoolean()) {
overriddenHostnames.add(name);
}
}

View File

@ -16,7 +16,6 @@
package io.netty.resolver.dns;
import io.netty.util.NetUtil;
import io.netty.util.internal.PlatformDependent;
import org.apache.directory.server.dns.DnsServer;
import org.apache.directory.server.dns.io.encoder.DnsMessageEncoder;
import org.apache.directory.server.dns.io.encoder.ResourceRecordEncoder;
@ -52,7 +51,9 @@ import java.util.LinkedHashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import java.util.concurrent.ThreadLocalRandom;
class TestDnsServer extends DnsServer {
private static final Map<String, byte[]> BYTES = new HashMap<>();
@ -251,7 +252,7 @@ class TestDnsServer extends DnsServer {
}
private static int index(int arrayLength) {
return Math.abs(PlatformDependent.threadLocalRandom().nextInt()) % arrayLength;
return Math.abs(ThreadLocalRandom.current().nextInt()) % arrayLength;
}
private static String nextDomain() {
@ -285,19 +286,19 @@ class TestDnsServer extends DnsServer {
case A:
do {
attr.put(DnsAttribute.IP_ADDRESS.toLowerCase(Locale.US), nextIp());
} while (PlatformDependent.threadLocalRandom().nextBoolean());
} while (ThreadLocalRandom.current().nextBoolean());
break;
case AAAA:
do {
attr.put(DnsAttribute.IP_ADDRESS.toLowerCase(Locale.US), nextIp6());
} while (PlatformDependent.threadLocalRandom().nextBoolean());
} while (ThreadLocalRandom.current().nextBoolean());
break;
case MX:
int priority = 0;
do {
attr.put(DnsAttribute.DOMAIN_NAME.toLowerCase(Locale.US), nextDomain());
attr.put(DnsAttribute.MX_PREFERENCE.toLowerCase(Locale.US), String.valueOf(++priority));
} while (PlatformDependent.threadLocalRandom().nextBoolean());
} while (ThreadLocalRandom.current().nextBoolean());
break;
default:
return null;

View File

@ -19,7 +19,6 @@ import io.netty.util.concurrent.EventExecutor;
import io.netty.util.concurrent.Future;
import io.netty.util.concurrent.FutureListener;
import io.netty.util.concurrent.Promise;
import io.netty.util.internal.PlatformDependent;
import io.netty.util.internal.UnstableApi;
import java.net.InetAddress;
@ -28,6 +27,7 @@ import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.ThreadLocalRandom;
/**
* A {@link NameResolver} that resolves {@link InetAddress} and force Round Robin by choosing a single address
@ -98,6 +98,6 @@ public class RoundRobinInetAddressResolver extends InetNameResolver {
}
private static int randomIndex(int numAddresses) {
return numAddresses == 1 ? 0 : PlatformDependent.threadLocalRandom().nextInt(numAddresses);
return numAddresses == 1 ? 0 : ThreadLocalRandom.current().nextInt(numAddresses);
}
}

View File

@ -26,7 +26,6 @@ import io.netty.channel.ChannelOption;
import io.netty.channel.DefaultFileRegion;
import io.netty.channel.FileRegion;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.internal.PlatformDependent;
import org.junit.Test;
import java.io.File;
@ -35,6 +34,7 @@ import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.WritableByteChannel;
import java.util.Random;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.atomic.AtomicReference;
import static org.hamcrest.CoreMatchers.is;
@ -45,7 +45,7 @@ public class SocketFileRegionTest extends AbstractSocketTest {
static final byte[] data = new byte[1048576 * 10];
static {
PlatformDependent.threadLocalRandom().nextBytes(data);
ThreadLocalRandom.current().nextBytes(data);
}
@Test
@ -104,7 +104,7 @@ public class SocketFileRegionTest extends AbstractSocketTest {
file.deleteOnExit();
final FileOutputStream out = new FileOutputStream(file);
final Random random = PlatformDependent.threadLocalRandom();
final Random random = ThreadLocalRandom.current();
// Prepend random data which will not be transferred, so that we can test non-zero start offset
final int startOffset = random.nextInt(8192);

View File

@ -26,6 +26,7 @@ import io.netty.util.internal.logging.InternalLoggerFactory;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.atomic.AtomicInteger;
import static io.netty.util.internal.MacAddressUtil.defaultMachineId;
@ -145,7 +146,7 @@ public final class DefaultChannelId implements ChannelId {
}
if (pid < 0) {
pid = PlatformDependent.threadLocalRandom().nextInt();
pid = ThreadLocalRandom.current().nextInt();
logger.warn("Failed to find the current process ID from '{}'; using a random value: {}", value, pid);
}
@ -176,7 +177,7 @@ public final class DefaultChannelId implements ChannelId {
i = writeLong(i, Long.reverse(System.nanoTime()) ^ System.currentTimeMillis());
// random
int random = PlatformDependent.threadLocalRandom().nextInt();
int random = ThreadLocalRandom.current().nextInt();
i = writeInt(i, random);
assert i == data.length;

View File

@ -34,7 +34,6 @@ import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.util.CharsetUtil;
import io.netty.util.NetUtil;
import io.netty.util.internal.PlatformDependent;
import org.junit.Test;
import java.io.DataInput;
@ -52,6 +51,7 @@ import java.nio.channels.NetworkChannel;
import java.util.Queue;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadLocalRandom;
import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.*;
@ -166,7 +166,7 @@ public class NioSocketChannelTest extends AbstractNioChannelTest<NioSocketChanne
// Just some random bytes
byte[] bytes = new byte[1024];
PlatformDependent.threadLocalRandom().nextBytes(bytes);
ThreadLocalRandom.current().nextBytes(bytes);
Channel sc = null;
Channel cc = null;