下面列出了怎么用io.netty.util.internal.ThreadLocalRandom的API类实例代码及写法,或者点击链接到github查看源代码。
@Override
public void channelActive(ChannelHandlerContext ctx) {
ThreadLocalRandom random = ThreadLocalRandom.current();
int delay = random.nextInt(5, 10);
// 每一条新连接,都是5~10秒之后发消息
ctx.executor().scheduleAtFixedRate(() -> {
PushMessage pushMessage = new PushMessage();
pushMessage.setMessageId(UUID.randomUUID().toString());
pushMessage.setContent("hello,world!");
pushMessage.setTimestamp(System.currentTimeMillis());
messageStorage.setObject(pushMessage.getMessageId(), pushMessage);
ctx.channel().writeAndFlush(pushMessage);
}, delay, delay, TimeUnit.SECONDS);
}
private void testInternalNioBuffer(int a) {
ByteBuf buffer = releaseLater(newBuffer(2));
ByteBuffer buf = buffer.internalNioBuffer(0, 1);
assertEquals(1, buf.remaining());
byte[] data = new byte[a];
ThreadLocalRandom.current().nextBytes(data);
buffer.writeBytes(data);
buf = buffer.internalNioBuffer(0, a);
assertEquals(a, buf.remaining());
for (int i = 0; i < a; i++) {
assertEquals(data[i], buf.get());
}
assertFalse(buf.hasRemaining());
}
/**
* Returns a (probably) non-empty steal queue, if one is found
* during a scan, else null. This method must be retried by
* caller if, by the time it tries to use the queue, it is empty.
*/
private WorkQueue findNonEmptyStealQueue() {
int r = ThreadLocalRandom.current().nextInt();
for (;;) {
int ps = plock, m; WorkQueue[] ws; WorkQueue q;
if ((ws = workQueues) != null && (m = ws.length - 1) >= 0) {
for (int j = (m + 1) << 2; j >= 0; --j) {
if ((q = ws[(((r - j) << 1) | 1) & m]) != null &&
q.base - q.top < 0)
return q;
}
}
if (plock == ps)
return null;
}
}
private void testInternalNioBuffer(int a) {
ByteBuf buffer = releaseLater(newBuffer(2));
ByteBuffer buf = buffer.internalNioBuffer(0, 1);
assertEquals(1, buf.remaining());
byte[] data = new byte[a];
ThreadLocalRandom.current().nextBytes(data);
buffer.writeBytes(data);
buf = buffer.internalNioBuffer(0, a);
assertEquals(a, buf.remaining());
for (int i = 0; i < a; i++) {
assertEquals(data[i], buf.get());
}
assertFalse(buf.hasRemaining());
}
private void benchArrayDequeue(final int repeats, final ArrayDeque<Integer> deque) {
int start = 0;
for (int i = 0; i < repeats; i++) {
List<Integer> tmpList = genData(start);
deque.addAll(tmpList);
// for (Integer o : tmpList) {
// deque.add(o);
// }
int removePos = start + ThreadLocalRandom.current().nextInt(tmpList.size());
deque.get(removePos - start);
int index = 0;
for (int j = 0; j < deque.size(); j++) {
if (deque.get(j) > removePos) {
index = j;
break;
}
}
if (index > 0) {
deque.removeRange(0, index);
}
start += tmpList.size();
}
}
private List<Integer> genData(final int start) {
int n = ThreadLocalRandom.current().nextInt(500) + 10;
List<Integer> tmpList = new ArrayList<>(n);
for (int i = 0; i < n; i++) {
tmpList.add(i + start);
}
return tmpList;
}
private void benchSegmentList(final int repeats) {
int start = 0;
for (int i = 0; i < repeats; i++) {
List<Integer> tmpList = genData(start);
this.list.addAll(tmpList);
// for(Integer o: tmpList) {
// list.add(o);
// }
int removePos = start + ThreadLocalRandom.current().nextInt(tmpList.size());
this.list.get(removePos - start);
this.list.removeFromFirstWhen(x -> x <= removePos);
start += tmpList.size();
}
}
@Override
public void run() {
try {
List<GTable> tables = new ArrayList<>(humpback.getTables());
if (tables.size() == 0) {
return;
}
int idx = ThreadLocalRandom.current().nextInt(0, tables.size());
GTable gtable = tables.get(idx);
gtable.getMemTable().compact();
}
catch (Exception x) {
_log.error("", x);
}
}
public static int[] randomIntArray(final int length, final int range) {
final int[] array = new int[length];
final Random generator = ThreadLocalRandom.current();
for (int i = 0; i < array.length; i++) {
array[i] = generator.nextInt(range);
}
return array;
}
/**
* Acquires the plock lock to protect worker array and related
* updates. This method is called only if an initial CAS on plock
* fails. This acts as a spinlock for normal cases, but falls back
* to builtin monitor to block when (rarely) needed. This would be
* a terrible idea for a highly contended lock, but works fine as
* a more conservative alternative to a pure spinlock.
*/
private int acquirePlock() {
int spins = PL_SPINS, ps, nps;
for (;;) {
if (((ps = plock) & PL_LOCK) == 0 &&
U.compareAndSwapInt(this, PLOCK, ps, nps = ps + PL_LOCK))
return nps;
else if (spins >= 0) {
if (ThreadLocalRandom.current().nextInt() >= 0)
--spins;
}
else if (U.compareAndSwapInt(this, PLOCK, ps, ps | PL_SIGNAL)) {
synchronized (this) {
if ((plock & PL_SIGNAL) != 0) {
try {
wait();
} catch (InterruptedException ie) {
try {
Thread.currentThread().interrupt();
} catch (SecurityException ignore) {
}
}
}
else
notifyAll();
}
}
}
}
@Override
public String newId() {
final Instant now = Instant.now();
final int un2 = ThreadLocalRandom.current().nextInt(Integer.MAX_VALUE) & 0x7fffffff;
return JWT.create()
.withIssuer(issuer)
.withIssuedAt(Date.from(now))
.withExpiresAt(Date.from(now.plus(validSeconds, ChronoUnit.SECONDS)))
// To make multiple tokens issued in the same second unique, we add uniquifiers.
.withClaim(CLAIM_NAME_UNIQUIFIER1, un1)
.withClaim(CLAIM_NAME_UNIQUIFIER2, un2)
.sign(algorithm);
}
private static String getUniquifierPrefix() {
// To make a request ID globally unique, we will add MAC-based machine ID and a random number.
// The random number tries to make this instance unique in the same machine and process.
final byte[] r = TemporaryThreadLocals.get().byteArray(6);
ThreadLocalRandom.current().nextBytes(r);
final Encoder encoder = Base64.getEncoder();
return new StringBuilder().append(encoder.encodeToString(defaultMachineId()))
.append(encoder.encodeToString(r))
.toString();
}
private int getNextClientKeepAliveId() {
clientKeepAliveId++;
if (clientKeepAliveId < 1) {
clientKeepAliveId = (int) ((System.currentTimeMillis() % (60 * 1000)) << 4) + ThreadLocalRandom.current().nextInt(16) + 1;
}
return clientKeepAliveId;
}
private FileService() {
final long processId = Utils.getProcessId(ThreadLocalRandom.current().nextLong(10000, Integer.MAX_VALUE));
final long initialValue = Math.abs(processId << 45 | System.nanoTime() << 17 >> 17);
this.nextId.set(initialValue);
LOG.info("Initial file reader id in FileService is {}", initialValue);
}
private WeightDefinedEvent createWeightDefinedEvent() {
int weight = ThreadLocalRandom.current().nextInt() & Integer.MAX_VALUE;
WeightConfig config = new WeightConfig("group_1", UUID.randomUUID().toString(),
weight);
return new WeightDefinedEvent(new Object(), config);
}
/**
*
* @return a newly generated Delimiter (either for DATA or MIXED)
*/
private static String getNewMultipartDelimiter() {
// construct a generated delimiter
return Long.toHexString(ThreadLocalRandom.current().nextLong()).toLowerCase();
}
private static Random random() {
return ThreadLocalRandom.current();
}
public static RoundRobinProxyHandler createStatisticalRoundRobinHandler(
ClientFactory factory, ProxyRouteConfig config, SocketAddressHelper addressHelper) {
return new RoundRobinProxyHandler(factory, config, addressHelper, ThreadLocalRandom::current);
}
private RoundRobinProxyHandler(
ClientFactory factory, ProxyRouteConfig config, SocketAddressHelper addressHelper) {
this(factory, config, addressHelper, ThreadLocalRandom::current);
}
/**
* Generates a new pseudo-random integer within the specific range.
*
* This is essentially the same method that is present in Apache commons-lang. It is simply copied here to avoid
* bringing in a new dependency
*
* @param startInclusive the lowest value that can be generated
* @param endExclusive
* @return a pseurandom number in [startInclusive, endExclusive)
*/
private static int nextInt(final int startInclusive, final int endExclusive) {
if (startInclusive == endExclusive) {
return startInclusive;
}
return startInclusive + ThreadLocalRandom.current().nextInt(endExclusive - startInclusive);
}
/**
* Gets a new object id.
*
* @return the new id
*/
public static RandomId128 next() {
return new RandomId128(SystemClock.fast().mills(), ThreadLocalRandom.current().nextLong());
}
/**
* Gets a new object id.
*
* @return the new id
*/
public static RandomId next() {
return new RandomId(currentSeconds(), ThreadLocalRandom.current().nextLong());
}
/**
* = ThreadLocalRandom.current().nextInt(max)
*
* @param max
* @return
*/
public static final int nextInt(int max){
return ThreadLocalRandom.current().nextInt(max);
}