类io.netty.util.internal.ThreadLocalRandom源码实例Demo

下面列出了怎么用io.netty.util.internal.ThreadLocalRandom的API类实例代码及写法,或者点击链接到github查看源代码。

源代码1 项目: simple-message-push   文件: ChannelManager.java
@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);

}
 
源代码2 项目: netty4.0.27Learn   文件: AbstractByteBufTest.java
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());
}
 
源代码3 项目: netty4.0.27Learn   文件: ForkJoinPool.java
/**
 * 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;
    }
}
 
源代码4 项目: netty.book.kor   文件: AbstractByteBufTest.java
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());
}
 
源代码5 项目: sofa-jraft   文件: SegmentListTest.java
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();
    }
}
 
源代码6 项目: sofa-jraft   文件: SegmentListTest.java
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;
}
 
源代码7 项目: sofa-jraft   文件: SegmentListTest.java
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();
    }
}
 
源代码8 项目: antsdb   文件: Compactor.java
@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);
	}
}
 
源代码9 项目: netty4.0.27Learn   文件: UnitHelp.java
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;
}
 
源代码10 项目: netty4.0.27Learn   文件: ForkJoinPool.java
/**
 * 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();
            }
        }
    }
}
 
源代码11 项目: armeria   文件: JwtBasedSamlRequestIdManager.java
@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);
}
 
源代码12 项目: armeria   文件: JwtBasedSamlRequestIdManager.java
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();
}
 
源代码13 项目: ProtocolSupport   文件: KeepAliveCache.java
private int getNextClientKeepAliveId() {
	clientKeepAliveId++;
	if (clientKeepAliveId < 1) {
		clientKeepAliveId = (int) ((System.currentTimeMillis() % (60 * 1000)) << 4) + ThreadLocalRandom.current().nextInt(16) + 1;
	}
	return clientKeepAliveId;
}
 
源代码14 项目: sofa-jraft   文件: FileService.java
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);
}
 
源代码16 项目: netty4.0.27Learn   文件: HttpPostRequestEncoder.java
/**
 *
 * @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();
}
 
源代码18 项目: xio   文件: RoundRobinProxyHandler.java
public static RoundRobinProxyHandler createStatisticalRoundRobinHandler(
    ClientFactory factory, ProxyRouteConfig config, SocketAddressHelper addressHelper) {
  return new RoundRobinProxyHandler(factory, config, addressHelper, ThreadLocalRandom::current);
}
 
源代码19 项目: xio   文件: RoundRobinProxyHandler.java
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);
}
 
源代码21 项目: turbo-rpc   文件: RandomId128.java
/**
 * Gets a new object id.
 *
 * @return the new id
 */
public static RandomId128 next() {
	return new RandomId128(SystemClock.fast().mills(), ThreadLocalRandom.current().nextLong());
}
 
源代码22 项目: turbo-rpc   文件: RandomId.java
/**
 * Gets a new object id.
 *
 * @return the new id
 */
public static RandomId next() {
	return new RandomId(currentSeconds(), ThreadLocalRandom.current().nextLong());
}
 
源代码23 项目: Ak47   文件: RandomUtil.java
/**
 * = ThreadLocalRandom.current().nextInt(max)
 * 
 * @param max
 * @return
 */
public static final int nextInt(int max){
    return ThreadLocalRandom.current().nextInt(max);
}
 
 类所在包
 类方法
 同包方法