下面列出了java.util.concurrent.ThreadLocalRandom#nextLong ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* 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));
}
}
/** 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();
}
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;
}
@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());
}
}
/**
* 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;
}
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);
}
/**
* 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) {}
}
}
/**
* Default constructor.
*/
public TestObject() {
ThreadLocalRandom rnd = ThreadLocalRandom.current();
id = rnd.nextLong();
len = rnd.nextInt(32 * 1024);
arr = new byte[len];
rnd.nextBytes(arr);
}
@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);
}
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());
}
}
@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);
}
}
}
/***************************************
* 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();
}
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");
}
/**
* 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) {}
}
}
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;
}
/**
* @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;
}
@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());
}
@Override
public UUID createUuid() {
ThreadLocalRandom random = ThreadLocalRandom.current();
return new UUID(random.nextLong(), random.nextLong());
}
/**
* @return Random timeout.
*/
protected long randomTimeOut() {
ThreadLocalRandom random = ThreadLocalRandom.current();
return random.nextLong(5, 20);
}
public static UUID fastUUID() {
ThreadLocalRandom random = ThreadLocalRandom.current();
return new UUID(random.nextLong(), random.nextLong());
}