下面列出了java.util.concurrent.ThreadLocalRandom#current ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* Check concurrent operations.
*
* @param done Done flag.
* @param node Node.
*/
private static void checkConcurrentOperations(AtomicBoolean done, Ignite node) {
ThreadLocalRandom rnd = ThreadLocalRandom.current();
boolean state = rnd.nextBoolean();
while (!done.get()) {
if (state)
node.cluster().enableWal(CACHE_NAME);
else
node.cluster().disableWal(CACHE_NAME);
state = !state;
}
try {
Thread.sleep(rnd.nextLong(200, 1000));
}
catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
public void update(@HttpQueryParameter("queries") String queries, Connection connection,
ObjectResponse<World[]> response) throws SQLException {
ThreadLocalRandom random = ThreadLocalRandom.current();
int count = getQueryCount(queries);
World[] worlds = new World[count];
try (PreparedStatement statement = connection.prepareStatement("SELECT ID FROM WORLD WHERE ID = ?",
ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY)) {
for (int i = 0; i < worlds.length; i++) {
statement.setInt(1, random.nextInt(1, 10001));
ResultSet resultSet = statement.executeQuery();
resultSet.next();
worlds[i] = new World(resultSet.getInt(1), random.nextInt(1, 10001));
}
}
Arrays.sort(worlds, (a, b) -> a.getId() - b.getId());
try (PreparedStatement statement = connection
.prepareStatement("UPDATE WORLD SET RANDOMNUMBER = ? WHERE ID = ?")) {
for (int u = 0; u < worlds.length; u++) {
statement.setInt(1, worlds[u].getRandomNumber());
statement.setInt(2, worlds[u].getId());
statement.addBatch();
}
statement.executeBatch();
}
response.send(worlds);
}
/** */
protected void loadData(IgniteEx node, int start, int end) {
try (IgniteDataStreamer<Object, Object> streamer = node.dataStreamer(POI_CACHE_NAME)) {
Random rnd = ThreadLocalRandom.current();
for (int i = start; i < end; i++) {
BinaryObject bo = node.binary().builder(POI_CLASS_NAME)
.setField(NAME_FIELD_NAME, "POI_" + i, String.class)
.setField(LATITUDE_FIELD_NAME, rnd.nextDouble(), Double.class)
.setField(LONGITUDE_FIELD_NAME, rnd.nextDouble(), Double.class)
.build();
streamer.addData(i, bo);
}
}
}
/**
* Each of a parallel sized stream of bounded ints is within bounds
*/
public void testBoundedInts() {
AtomicInteger fails = new AtomicInteger(0);
ThreadLocalRandom r = ThreadLocalRandom.current();
long size = 12345L;
for (int least = -15485867; least < MAX_INT_BOUND; least += 524959) {
for (int bound = least + 2; bound > least && bound < MAX_INT_BOUND; bound += 67867967) {
final int lo = least, hi = bound;
r.ints(size, lo, hi).parallel().
forEach(x -> {
if (x < lo || x >= hi)
fails.getAndIncrement();
});
}
}
assertEquals(fails.get(), 0);
}
private List<BrokerGroup> select(final List<BrokerGroup> groups) {
if (groups == null || groups.size() == 0) {
return Collections.EMPTY_LIST;
}
if (groups.size() <= DEFAULT_MIN_NUM) {
return groups;
}
final ThreadLocalRandom random = ThreadLocalRandom.current();
final Set<BrokerGroup> resultSet = new HashSet<>(DEFAULT_MIN_NUM);
while (resultSet.size() <= DEFAULT_MIN_NUM) {
final int randomIndex = random.nextInt(groups.size());
resultSet.add(groups.get(randomIndex));
}
return new ArrayList<>(resultSet);
}
@Override
public JChannelGroup select(CopyOnWriteGroupList groups, Directory directory) {
JChannelGroup[] elements = groups.getSnapshot();
int length = elements.length;
if (length == 0) {
return null;
}
if (length == 1) {
return elements[0];
}
WeightArray weightArray = (WeightArray) groups.getWeightArray(elements, directory.directoryString());
if (weightArray == null || weightArray.length() != length) {
weightArray = WeightSupport.computeWeights(groups, elements, directory);
}
ThreadLocalRandom random = ThreadLocalRandom.current();
if (weightArray.isAllSameWeight()) {
return elements[random.nextInt(length)];
}
int nextIndex = getNextServerIndex(weightArray, length, random);
return elements[nextIndex];
}
private int randomColor() {
ThreadLocalRandom random = ThreadLocalRandom.current();
double rand = random.nextDouble(1, 100);
if (rand <= 0.164) {
return DyeColor.PINK.getDyedData();
}
if (rand <= 15) {
return random.nextBoolean() ? DyeColor.BLACK.getDyedData() : random.nextBoolean() ? DyeColor.GRAY.getDyedData() : DyeColor.LIGHT_GRAY.getDyedData();
}
return DyeColor.WHITE.getDyedData();
}
/**
* A sequential unsized stream of longs generates at least 100 values
*/
public void testUnsizedLongsCountSeq() {
LongAdder counter = new LongAdder();
ThreadLocalRandom r = ThreadLocalRandom.current();
long size = 100;
r.longs().limit(size).forEach(x -> {
counter.increment();
});
assertEquals(counter.sum(), size);
}
/**
* Returns true iff this BigInteger passes the specified number of
* Miller-Rabin tests. This test is taken from the DSA spec (NIST FIPS
* 186-2).
*
* The following assumptions are made:
* This BigInteger is a positive, odd number greater than 2.
* iterations<=50.
*/
private boolean passesMillerRabin(int iterations, Random rnd) {
// Find a and m such that m is odd and this == 1 + 2**a * m
BigInteger thisMinusOne = this.subtract(ONE);
BigInteger m = thisMinusOne;
int a = m.getLowestSetBit();
m = m.shiftRight(a);
// Do the tests
if (rnd == null) {
rnd = ThreadLocalRandom.current();
}
for (int i=0; i < iterations; i++) {
// Generate a uniform random on (1, this)
BigInteger b;
do {
b = new BigInteger(this.bitLength(), rnd);
} while (b.compareTo(ONE) <= 0 || b.compareTo(this) >= 0);
int j = 0;
BigInteger z = b.modPow(m, this);
while (!((j == 0 && z.equals(ONE)) || z.equals(thisMinusOne))) {
if (j > 0 && z.equals(ONE) || ++j == a)
return false;
z = z.modPow(TWO, this);
}
}
return true;
}
private static Object randomValue(Class<?> type) {
var random = ThreadLocalRandom.current();
if (type == UUID.class) {
return UUID.randomUUID();
}
if (type == LocalDate.class) {
return LocalDate.of(
random.nextInt(2000, 2100),
random.nextInt(Month.JANUARY.getValue(), Month.DECEMBER.getValue() + 1),
random.nextInt(1, Month.FEBRUARY.minLength() + 1));
}
if (type == Money.class) {
return Money.of(
random.nextDouble(0, 1000),
pickRandom(Monetary.getCurrencies()));
}
if (type == Instant.class) {
return Instant.ofEpochMilli(random.nextLong());
}
if (type == ZonedDateTime.class) {
var zoneIds = ZoneId.getAvailableZoneIds();
zoneIds.remove("GMT0"); // XXX: cannot be parsed by java.time.format.DateTimeFormatterBuilder.appendZoneRegionId - fixed in Java 9 https://bugs.openjdk.java.net/browse/JDK-8138664
var zoneId = ZoneId.of(pickRandom(zoneIds));
return Instant.ofEpochMilli(random.nextLong()).atZone(zoneId);
}
if (type == String.class) {
return RandomStringUtils.randomAlphanumeric(random.nextInt(10));
}
if (type == int.class) {
return random.nextInt();
}
if (type == Class.class) {
return pickRandom(Arrays.asList(Integer.class, Long.class, Float.class, Double.class));
}
throw new IllegalArgumentException("Unsupported type: " + type);
}
/**
* A sequential unsized stream of doubles generates at least 100 values
*/
public void testUnsizedDoublesCountSeq() {
LongAdder counter = new LongAdder();
ThreadLocalRandom r = ThreadLocalRandom.current();
long size = 100;
r.doubles().limit(size).forEach(x -> {
counter.increment();
});
assertEquals(counter.sum(), size);
}
/**
* A parallel sized stream of doubles generates the given number of values
*/
public void testDoublesCount() {
LongAdder counter = new LongAdder();
ThreadLocalRandom r = ThreadLocalRandom.current();
long size = 0;
for (int reps = 0; reps < REPS; ++reps) {
counter.reset();
r.doubles(size).parallel().forEach(x -> {
counter.increment();
});
assertEquals(counter.sum(), size);
size += 524959;
}
}
/**
* This simple test compares the output of {@link BaseState#xxHash64(long, long, long)} with the
* output of {@link net.openhft.hashing.LongHashFunction}, that itself is tested against the
* reference implementation in C. This increase confidence that the xxHash function implemented
* in this package is in fact the same xxHash function implemented in C.
*
* @author Roman Leventov
* @author Lee Rhodes
*/
@Test
public void testXxHash() {
Random random = ThreadLocalRandom.current();
for (int len = 0; len < 100; len++) {
byte[] bytes = new byte[len];
for (int i = 0; i < 10; i++) {
long zahXxHash = LongHashFunction.xx().hashBytes(bytes);
long memoryXxHash = Memory.wrap(bytes).xxHash64(0, len, 0);
assertEquals(memoryXxHash, zahXxHash);
random.nextBytes(bytes);
}
}
}
void fillBuffer(SourceBuilder.TimestampedSourceBuffer<Trade> buffer) {
ThreadLocalRandom rnd = ThreadLocalRandom.current();
for (int i = 0; i < tradesPerSec; i++) {
String ticker = symbols.get(rnd.nextInt(symbols.size()));
long tradeTime = System.currentTimeMillis();
Trade trade = new Trade(tradeTime, ticker, QUANTITY, rnd.nextInt(5000));
buffer.add(trade, tradeTime);
}
LockSupport.parkNanos(TimeUnit.SECONDS.toNanos(1)); // sleep for 1 second
}
/**
* A parallel sized stream of doubles generates the given number of values
*/
public void testDoublesCount() {
LongAdder counter = new LongAdder();
ThreadLocalRandom r = ThreadLocalRandom.current();
long size = 0;
for (int reps = 0; reps < REPS; ++reps) {
counter.reset();
r.doubles(size).parallel().forEach(x -> {
counter.increment();
});
assertEquals(counter.sum(), size);
size += 524959;
}
}
public JinjavaInterpreter(
Jinjava application,
Context context,
JinjavaConfig renderConfig
) {
this.context = context;
this.config = renderConfig;
this.application = application;
switch (config.getRandomNumberGeneratorStrategy()) {
case THREAD_LOCAL:
random = ThreadLocalRandom.current();
break;
case CONSTANT_ZERO:
random = new ConstantZeroRandomNumberGenerator();
break;
case DEFERRED:
random = new DeferredRandomNumberGenerator();
break;
default:
throw new IllegalStateException(
"No random number generator with strategy " +
config.getRandomNumberGeneratorStrategy()
);
}
this.expressionResolver =
new ExpressionResolver(this, application.getExpressionFactory());
}
@Override
protected RpcClientEntity loadBalance(RpcClientEntity rpcClientEntity , String interfaceName, List<NettyClient> candidates) {
if (candidates == null || candidates.size() == 0) {
return null;
}
ThreadLocalRandom threadLocalRandom = ThreadLocalRandom.current();
int index = threadLocalRandom.nextInt( candidates.size() );
NettyClient nettyClient=candidates.get( index );
RpcClientEntity entity=new RpcClientEntity();
BeanUtils.copyProperties( nettyClient,entity );
entity.setIsSyn( rpcClientEntity.isSyn() );
entity.setRpcClz( rpcClientEntity.getRpcClz() );
return entity;
}
public WobbleStroke(float detail, float amplitude, float basicStrokeWidth) {
this.detail = detail;
this.amplitude = amplitude;
this.basicStrokeWidth = basicStrokeWidth;
//noinspection SharedThreadLocalRandom
rand = ThreadLocalRandom.current();
// seed = System.nanoTime();
}
@Override()
public Array<T> shuffle(int count) {
final Random random = ThreadLocalRandom.current();
final int length = length();
for (int i=0; i<count; ++i) {
for (int j=0; j<length; ++j) {
this.swap(j, random.nextInt(length));
}
}
return this;
}
public TraceContext(@Nullable TraceContext parent) {
Random prng = ThreadLocalRandom.current();
this.spanId = String.format("%016x", prng.nextLong());
this.traceId = parent == null || parent.getTraceId().trim().isEmpty()
? nextTraceIdHigh(prng) + this.spanId
: parent.getTraceId();
this.parentId = parent == null || parent.getSpanId().trim().isEmpty()
? null
: parent.getSpanId();
}