Java Code Examples for java.util.concurrent.ThreadLocalRandom#nextLong()

The following examples show how to use java.util.concurrent.ThreadLocalRandom#nextLong() . 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: SkipListUtilsTest.java    From flink with Apache License 2.0 6 votes vote down vote up
private KeySpace createKeySpace(int level, int keyLen) {
	ThreadLocalRandom random = ThreadLocalRandom.current();
	KeySpace keySpace = new KeySpace();
	keySpace.level = level;
	keySpace.status = random.nextBoolean() ? NodeStatus.PUT : NodeStatus.REMOVE;
	keySpace.valuePointer = random.nextLong();
	keySpace.nextKeyPointer = random.nextLong();
	keySpace.nextIndexNodes = new long[level];
	keySpace.prevIndexNodes = new long[level];
	for (int i = 0; i < level; i++) {
		keySpace.nextIndexNodes[i] = random.nextLong();
		keySpace.prevIndexNodes[i] = random.nextLong();
	}
	keySpace.keyData = new byte[keyLen];
	random.nextBytes(keySpace.keyData);
	return keySpace;
}
 
Example 2
Source File: Values10.java    From ignite with Apache License 2.0 6 votes vote down vote up
/** Creates new object with randomly initialized fields */
public Values10() {
    ThreadLocalRandom rnd = ThreadLocalRandom.current();

    val1 = String.valueOf(rnd.nextLong());
    val2 = rnd.nextLong();

    val3 = String.valueOf(rnd.nextLong());
    val4 = rnd.nextLong();

    val5 = String.valueOf(rnd.nextLong());
    val6 = rnd.nextLong();

    val7 = String.valueOf(rnd.nextLong());
    val8 = rnd.nextLong();

    val9 = String.valueOf(rnd.nextLong());
    val10 = rnd.nextLong();
}
 
Example 3
Source File: QueryFactory.java    From ignite with Apache License 2.0 6 votes vote down vote up
/**
 * Fills specified prepared statement with random values and specified id (primary key).
 *
 * @param stmt prepared statement, built from {@link #insert} query.
 * @param id id in the test table.
 * @throws SQLException if statement is not correct.
 */
public void setRandomInsertArgs(PreparedStatement stmt, long id) throws SQLException {
    stmt.setLong(1, id);
    ThreadLocalRandom rnd = ThreadLocalRandom.current();

    for (int vi = 1; vi <= valFieldsCnt; vi++) {
        // vi is value index (among all values), but we also have "id" which is primary key
        // so index in query is value index shifted by 1.
        int qryIdx = vi + 1;

        long nextVal = rnd.nextLong();

        if (vi % 2 == 1)
            stmt.setLong(qryIdx, nextVal);
        else
            stmt.setString(qryIdx, String.valueOf(nextVal));
    }
}
 
Example 4
Source File: InternalPriorityQueueTestBase.java    From flink with Apache License 2.0 5 votes vote down vote up
protected static void insertRandomElements(
	@Nonnull InternalPriorityQueue<TestElement> priorityQueue,
	@Nonnull Set<TestElement> checkSet,
	int count) {

	ThreadLocalRandom localRandom = ThreadLocalRandom.current();

	final int numUniqueKeys = Math.max(count / 4, 64);

	long duplicatePriority = Long.MIN_VALUE;

	final boolean checkEndSizes = priorityQueue.isEmpty();

	for (int i = 0; i < count; ++i) {
		TestElement element;
		do {
			long elementPriority;
			if (duplicatePriority == Long.MIN_VALUE) {
				elementPriority = localRandom.nextLong();
			} else {
				elementPriority = duplicatePriority;
				duplicatePriority = Long.MIN_VALUE;
			}
			element = new TestElement(localRandom.nextInt(numUniqueKeys), elementPriority);
		} while (!checkSet.add(element));

		if (localRandom.nextInt(10) == 0) {
			duplicatePriority = element.getPriority();
		}

		final boolean headChangedIndicated = priorityQueue.add(element);
		if (element.equals(priorityQueue.peek())) {
			Assert.assertTrue(headChangedIndicated);
		}
	}

	if (checkEndSizes) {
		Assert.assertEquals(count, priorityQueue.size());
	}
}
 
Example 5
Source File: ThreadLocalPerformance.java    From commons-rng with Apache License 2.0 5 votes vote down vote up
/**
 * @return the result
 */
@Benchmark
@Threads(4)
public long threadLocalRandom() {
    final ThreadLocalRandom rng = ThreadLocalRandom.current();
    long result = 0;
    for (int i = 0; i < numValues; i++) {
        result = result ^ rng.nextLong();
    }
    return result;
}
 
Example 6
Source File: SkipListUtilsTest.java    From flink with Apache License 2.0 5 votes vote down vote up
private ValueSpace createValueSpace(int valueLen) {
	ThreadLocalRandom random = ThreadLocalRandom.current();
	ValueSpace valueSpace = new ValueSpace();
	valueSpace.version = random.nextInt(Integer.MAX_VALUE);
	valueSpace.keyPointer = random.nextLong();
	valueSpace.nextValuePointer = random.nextLong();
	valueSpace.valueData = new byte[valueLen];
	random.nextBytes(valueSpace.valueData);
	return valueSpace;
}
 
Example 7
Source File: ThreadLocalRandomTest.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * nextLong(least >= bound) throws IllegalArgumentException
 */
public void testNextLongBadBounds() {
    long[][] badBoundss = {
        { 17L, 2L },
        { -42L, -42L },
        { Long.MAX_VALUE, Long.MIN_VALUE },
    };
    ThreadLocalRandom rnd = ThreadLocalRandom.current();
    for (long[] badBounds : badBoundss) {
        try {
            rnd.nextLong(badBounds[0], badBounds[1]);
            shouldThrow();
        } catch (IllegalArgumentException success) {}
    }
}
 
Example 8
Source File: PinotSegmentUtil.java    From incubator-pinot with Apache License 2.0 5 votes vote down vote up
private static Object generateTimeValue(ThreadLocalRandom random, TimeUnit unit) {
  final long milliMin = TimeUtils.getValidMinTimeMillis();
  final long milliMax = TimeUtils.getValidMaxTimeMillis();
  final long daysMin = TimeUnit.DAYS.convert(milliMin, TimeUnit.MILLISECONDS);
  final long daysMax = TimeUnit.DAYS.convert(milliMax, TimeUnit.MILLISECONDS);
  final long hoursMin = TimeUnit.HOURS.convert(milliMin, TimeUnit.MILLISECONDS);
  final long hoursMax = TimeUnit.HOURS.convert(milliMax, TimeUnit.MILLISECONDS);
  final long minutesMin = TimeUnit.MINUTES.convert(milliMin, TimeUnit.MILLISECONDS);
  final long minutesMax = TimeUnit.MINUTES.convert(milliMax, TimeUnit.MILLISECONDS);
  switch (unit) {
    case MILLISECONDS:
      return random.nextLong(milliMin, milliMax);
    case SECONDS:
      return random.nextLong(milliMin/1000, milliMax/1000);
    case MICROSECONDS:
      return random.nextLong(milliMin*1000, milliMax*1000);
    case NANOSECONDS:
      return random.nextLong(milliMin*1000*1000, milliMax*1000*1000);
    case DAYS:
      return random.nextLong(daysMin, daysMax);
    case HOURS:
      return random.nextLong(hoursMin, hoursMax);
    case MINUTES:
      return random.nextLong(minutesMin, minutesMax);
  }
  throw new IllegalStateException("Illegal data type");
}
 
Example 9
Source File: ForkJoinExample.java    From coroutines with Apache License 2.0 5 votes vote down vote up
/***************************************
 * Main.
 *
 * @param rArgs
 */
public static void main(String[] rArgs)
{
	ThreadLocalRandom rRandom	    = ThreadLocalRandom.current();
	long[]			  aCoefficients = new long[TASK_SIZE];

	for (int i = 0; i < TASK_SIZE; i++)
	{
		aCoefficients[i] = rRandom.nextLong(0, 1024 * 1024);
	}

	Profiler aProfiler =
		new Profiler(ForkJoinExample.class.getSimpleName());

	ScopeFuture<DoubleAdder> aResult =
		produce(
			RESULT,
			scope -> computeOrSplit(scope, aCoefficients, 0, TASK_SIZE));

	System.out.printf("Sum: %f\n", aResult.get().sum());

	aProfiler.measure(
		String.format(
			"%d tasks\nwith a batch size of %d",
			TASK_SIZE,
			BATCH_SIZE));
	aProfiler.printSummary();
}
 
Example 10
Source File: ItemTransactionGeneratorSource.java    From flink-tutorials with Apache License 2.0 5 votes vote down vote up
@Override
public void run(SourceContext<ItemTransaction> ctx) throws Exception {
	ThreadLocalRandom rnd = ThreadLocalRandom.current();
	ParetoDistribution paretoDistribution = new ParetoDistribution(numItems, shape);

	LOG.info("Starting transaction generator for {} items and {} sleep", numItems, sleep);

	while (isRunning) {
		long nextItemId;
		do {
			nextItemId = sample(paretoDistribution);
		} while (nextItemId > numItems);
		String itemId = "item_" + nextItemId;

		int quantity = (int) (Math.round(rnd.nextGaussian() / 2 * 10) * 10) + 5;
		if (quantity == 0) {
			continue;
		}
		long transactionId = rnd.nextLong(Long.MAX_VALUE);
		synchronized (ctx.getCheckpointLock()) {
			ctx.collect(new ItemTransaction(transactionId, System.currentTimeMillis(), itemId, quantity));
		}
		if (sleep > 0) {
			Thread.sleep(sleep);
		}
	}

}
 
Example 11
Source File: RandomIdsGenerator.java    From opentelemetry-java with Apache License 2.0 5 votes vote down vote up
@Override
public TraceId generateTraceId() {
  long idHi;
  long idLo;
  ThreadLocalRandom random = ThreadLocalRandom.current();
  do {
    idHi = random.nextLong();
    idLo = random.nextLong();
  } while (idHi == INVALID_ID && idLo == INVALID_ID);
  return new TraceId(idHi, idLo);
}
 
Example 12
Source File: SegmentedRingByteBufferTest.java    From ignite with Apache License 2.0 5 votes vote down vote up
/**
 * Default constructor.
 */
public TestObject() {
    ThreadLocalRandom rnd = ThreadLocalRandom.current();

    id = rnd.nextLong();
    len = rnd.nextInt(32 * 1024);
    arr = new byte[len];

    rnd.nextBytes(arr);
}
 
Example 13
Source File: ThreadLocalRandomTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
/**
 * nextLong(least >= bound) throws IllegalArgumentException
 */
public void testNextLongBadBounds() {
    long[][] badBoundss = {
        { 17L, 2L },
        { -42L, -42L },
        { Long.MAX_VALUE, Long.MIN_VALUE },
    };
    ThreadLocalRandom rnd = ThreadLocalRandom.current();
    for (long[] badBounds : badBoundss) {
        try {
            rnd.nextLong(badBounds[0], badBounds[1]);
            shouldThrow();
        } catch (IllegalArgumentException success) {}
    }
}
 
Example 14
Source File: CloudHBaseSinkFunctionExample.java    From alibaba-flink-connectors with Apache License 2.0 5 votes vote down vote up
private Tuple3<Boolean, Long, Row> getPutTuple() {
	ThreadLocalRandom random = ThreadLocalRandom.current();
	long rowKey = random.nextLong();
	Row row = new Row(columnNames.getArity());
	for (int i = 0; i < columnNames.getArity(); i++) {
		row.setField(i, random.nextDouble());
	}
	return Tuple3.of(true, rowKey, row);
}
 
Example 15
Source File: UserWorker.java    From Bats with Apache License 2.0 5 votes vote down vote up
/**
 * Helper method to generate QueryId
 * @return generated QueryId
 */
private static QueryId queryIdGenerator() {
  ThreadLocalRandom r = ThreadLocalRandom.current();

  // create a new queryid where the first four bytes are a growing time (each new value comes earlier in sequence).  Last 12 bytes are random.
  final long time = (int) (System.currentTimeMillis()/1000);
  final long p1 = ((Integer.MAX_VALUE - time) << 32) + r.nextInt();
  final long p2 = r.nextLong();
  final QueryId id = QueryId.newBuilder().setPart1(p1).setPart2(p2).build();
  return id;
}
 
Example 16
Source File: BenchmarkBlockDataToString.java    From hadoop-ozone with Apache License 2.0 5 votes vote down vote up
@Setup
public void createData() {
  ThreadLocalRandom rnd = ThreadLocalRandom.current();
  data = new ArrayList<>(count);
  values = new ArrayList<>(count);
  for (int i = 0; i < count; i++) {
    BlockID blockID = new BlockID(rnd.nextLong(), rnd.nextLong());
    BlockData item = new BlockData(blockID);
    item.setBlockCommitSequenceId(rnd.nextLong());
    data.add(item);
    values.add(item.toString());
  }
}
 
Example 17
Source File: TxWithSmallTimeoutAndContentionOneKeyTest.java    From ignite with Apache License 2.0 4 votes vote down vote up
/**
 * @return Random timeout.
 */
protected long randomTimeOut() {
    ThreadLocalRandom random = ThreadLocalRandom.current();

    return random.nextLong(5, 20);
}
 
Example 18
Source File: UuidSourceImpl.java    From cuba with Apache License 2.0 4 votes vote down vote up
@Override
public UUID createUuid() {
    ThreadLocalRandom random = ThreadLocalRandom.current();
    return new UUID(random.nextLong(), random.nextLong());
}
 
Example 19
Source File: IdUtil.java    From vjtools with Apache License 2.0 4 votes vote down vote up
public static UUID fastUUID() {
	ThreadLocalRandom random = ThreadLocalRandom.current();
	return new UUID(random.nextLong(), random.nextLong());
}
 
Example 20
Source File: RandomRetryWait.java    From sisyphus with Apache License 2.0 4 votes vote down vote up
@Override
public WaitTime waitTime(RetryWaitContext retryWaitContext) {
    ThreadLocalRandom random = ThreadLocalRandom.current();
    long time = random.nextLong(retryWaitContext.min(), retryWaitContext.max()-retryWaitContext.min());
    return super.rangeCorrect(time, retryWaitContext.min(), retryWaitContext.max());
}