io.netty.util.internal.ThreadLocalRandom Java Examples

The following examples show how to use io.netty.util.internal.ThreadLocalRandom. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: AbstractByteBufTest.java    From netty.book.kor with MIT License 6 votes vote down vote up
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());
}
 
Example #2
Source File: ForkJoinPool.java    From netty4.0.27Learn with Apache License 2.0 6 votes vote down vote up
/**
 * 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;
    }
}
 
Example #3
Source File: ChannelManager.java    From simple-message-push with MIT License 6 votes vote down vote up
@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);

}
 
Example #4
Source File: AbstractByteBufTest.java    From netty4.0.27Learn with Apache License 2.0 6 votes vote down vote up
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());
}
 
Example #5
Source File: SegmentListTest.java    From sofa-jraft with Apache License 2.0 5 votes vote down vote up
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();
    }
}
 
Example #6
Source File: KeepAliveCache.java    From ProtocolSupport with GNU Affero General Public License v3.0 5 votes vote down vote up
private int getNextClientKeepAliveId() {
	clientKeepAliveId++;
	if (clientKeepAliveId < 1) {
		clientKeepAliveId = (int) ((System.currentTimeMillis() % (60 * 1000)) << 4) + ThreadLocalRandom.current().nextInt(16) + 1;
	}
	return clientKeepAliveId;
}
 
Example #7
Source File: JwtBasedSamlRequestIdManager.java    From armeria with Apache License 2.0 5 votes vote down vote up
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();
}
 
Example #8
Source File: JwtBasedSamlRequestIdManager.java    From armeria with Apache License 2.0 5 votes vote down vote up
@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);
}
 
Example #9
Source File: ForkJoinPool.java    From netty4.0.27Learn with Apache License 2.0 5 votes vote down vote up
/**
 * 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();
            }
        }
    }
}
 
Example #10
Source File: UnitHelp.java    From netty4.0.27Learn with Apache License 2.0 5 votes vote down vote up
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;
}
 
Example #11
Source File: Compactor.java    From antsdb with GNU Lesser General Public License v3.0 5 votes vote down vote up
@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);
	}
}
 
Example #12
Source File: SegmentListTest.java    From sofa-jraft with Apache License 2.0 5 votes vote down vote up
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();
    }
}
 
Example #13
Source File: SegmentListTest.java    From sofa-jraft with Apache License 2.0 5 votes vote down vote up
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;
}
 
Example #14
Source File: HttpPostRequestEncoder.java    From netty4.0.27Learn with Apache License 2.0 4 votes vote down vote up
/**
 *
 * @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();
}
 
Example #15
Source File: ThreadLocalInsecureRandom.java    From netty4.0.27Learn with Apache License 2.0 4 votes vote down vote up
private static Random random() {
    return ThreadLocalRandom.current();
}
 
Example #16
Source File: WeightCalculatorWebFilterConcurrentTests.java    From spring-cloud-gateway with Apache License 2.0 4 votes vote down vote up
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);
}
 
Example #17
Source File: RoundRobinProxyHandler.java    From xio with Apache License 2.0 4 votes vote down vote up
public static RoundRobinProxyHandler createStatisticalRoundRobinHandler(
    ClientFactory factory, ProxyRouteConfig config, SocketAddressHelper addressHelper) {
  return new RoundRobinProxyHandler(factory, config, addressHelper, ThreadLocalRandom::current);
}
 
Example #18
Source File: RoundRobinProxyHandler.java    From xio with Apache License 2.0 4 votes vote down vote up
private RoundRobinProxyHandler(
    ClientFactory factory, ProxyRouteConfig config, SocketAddressHelper addressHelper) {
  this(factory, config, addressHelper, ThreadLocalRandom::current);
}
 
Example #19
Source File: FileService.java    From sofa-jraft with Apache License 2.0 4 votes vote down vote up
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);
}
 
Example #20
Source File: TestDelimitedLengthFieldBasedFrameDecoder.java    From datacollector with Apache License 2.0 3 votes vote down vote up
/**
 * 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);
}
 
Example #21
Source File: RandomId.java    From turbo-rpc with Apache License 2.0 2 votes vote down vote up
/**
 * Gets a new object id.
 *
 * @return the new id
 */
public static RandomId next() {
	return new RandomId(currentSeconds(), ThreadLocalRandom.current().nextLong());
}
 
Example #22
Source File: RandomId128.java    From turbo-rpc with Apache License 2.0 2 votes vote down vote up
/**
 * Gets a new object id.
 *
 * @return the new id
 */
public static RandomId128 next() {
	return new RandomId128(SystemClock.fast().mills(), ThreadLocalRandom.current().nextLong());
}
 
Example #23
Source File: RandomUtil.java    From Ak47 with Apache License 2.0 2 votes vote down vote up
/**
 * = ThreadLocalRandom.current().nextInt(max)
 * 
 * @param max
 * @return
 */
public static final int nextInt(int max){
    return ThreadLocalRandom.current().nextInt(max);
}