下面列出了java.util.concurrent.ThreadLocalRandom#nextBoolean ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
Runnable newEliminationStackRunner() {
final EliminationStack<Integer> stack = new EliminationStack<>();
return new Runnable() {
@Override public void run() {
final ThreadLocalRandom random = ThreadLocalRandom.current();
for (;;) {
if (random.nextBoolean()) {
stack.push(ELEMENT);
} else {
stack.pop();
}
calls.increment();
}
}
};
}
/**
* Concurrent Spliterators, once exhausted, stay exhausted.
*/
public void testStickySpliteratorExhaustion() throws Throwable {
if (!impl.isConcurrent()) return;
if (!testImplementationDetails) return;
final ThreadLocalRandom rnd = ThreadLocalRandom.current();
final Consumer alwaysThrows = e -> { throw new AssertionError(); };
final Collection c = impl.emptyCollection();
final Spliterator s = c.spliterator();
if (rnd.nextBoolean()) {
assertFalse(s.tryAdvance(alwaysThrows));
} else {
s.forEachRemaining(alwaysThrows);
}
final Object one = impl.makeElement(1);
// Spliterator should not notice added element
c.add(one);
if (rnd.nextBoolean()) {
assertFalse(s.tryAdvance(alwaysThrows));
} else {
s.forEachRemaining(alwaysThrows);
}
}
Runnable newLinkedTransferQueueRunner() {
final TransferQueue<Integer> queue = new LinkedTransferQueue<>();
return new Runnable() {
@Override public void run() {
final ThreadLocalRandom random = ThreadLocalRandom.current();
for (;;) {
if (random.nextBoolean()) {
queue.offer(ELEMENT);
} else {
queue.poll();
}
calls.increment();
}
}
};
}
/** {@inheritDoc} */
@Override public boolean test(Map<Object, Object> ctx) throws Exception {
ThreadLocalRandom rnd = ThreadLocalRandom.current();
if (rnd.nextBoolean()) {
double salary = rnd.nextDouble() * args.range() * 1000;
double maxSalary = salary + 1000;
Long res = (Long)cache().query(new SqlFieldsQuery("update Person set salary = (salary - ?1 + ?2) / 2 " +
"where salary >= ?1 and salary <= ?2").setArgs(salary, maxSalary)).getAll().get(0).get(0);
updItemsCnt.getAndAdd(res);
updCnt.getAndIncrement();
}
else {
int i = rnd.nextInt(args.range());
cache.put(i, new Person(i, "firstName" + i, "lastName" + i, i * 1000));
putCnt.getAndIncrement();
}
return true;
}
/** {@inheritDoc} */
@Override public boolean test(Map<Object, Object> ctx) throws Exception {
ThreadLocalRandom rnd = ThreadLocalRandom.current();
if (rnd.nextBoolean()) {
double salary = rnd.nextDouble() * args.range() * 1000;
double maxSalary = salary + 1000;
Long res = (Long)cache().query(new SqlFieldsQuery("delete from Person where salary >= ? and salary <= ?")
.setArgs(salary, maxSalary)).getAll().get(0).get(0);
delItemsCnt.getAndAdd(res);
delCnt.getAndIncrement();
}
else {
int i = rnd.nextInt(args.range());
cache.put(i, new Person(i, "firstName" + i, "lastName" + i, i * 1000));
putCnt.getAndIncrement();
}
return true;
}
/**
* 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);
}
}
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;
}
private Tuple3<Boolean, Long, Row> getDeleteTuple() {
ThreadLocalRandom random = ThreadLocalRandom.current();
long rowKey = random.nextLong();
Row row = new Row(columnNames.getArity());
for (int i = 0; i < columnNames.getArity(); i++) {
if (random.nextBoolean()) {
row.setField(i, true);
}
}
return Tuple3.of(false, rowKey, row);
}
private static void reverseImage(BufferedImage bufferedImg) {
ThreadLocalRandom random = ThreadLocalRandom.current();
if (random.nextBoolean()) {
int rgb;
for (int i=0; i<IMG_WIDTH; ++i) {
for (int j=0; j<IMG_HEIGHT; ++j) {
rgb = bufferedImg.getRGB(i, j);
bufferedImg.setRGB(i, j, 0xFFFFFF - rgb);
}
}
}
}
private String randomCase(String message) {
char[] messageArray = message.toCharArray();
ThreadLocalRandom rand = ThreadLocalRandom.current();
for (int i = 0; i < messageArray.length; i++) {
if (rand.nextBoolean()) {
messageArray[i] = Character.toUpperCase(messageArray[i]);
} else {
messageArray[i] = Character.toLowerCase(messageArray[i]);
}
}
return new String(messageArray);
}
private int randomColor() {
ThreadLocalRandom random = ThreadLocalRandom.current();
double rand = random.nextDouble(1, 100);
if (rand <= 0.164) {
return DyeColor.PINK.getWoolData();
}
if (rand <= 15) {
return random.nextBoolean() ? DyeColor.BLACK.getWoolData() : random.nextBoolean() ? DyeColor.GRAY.getWoolData() : DyeColor.LIGHT_GRAY.getWoolData();
}
return DyeColor.WHITE.getWoolData();
}
private int randomColor() {
ThreadLocalRandom random = ThreadLocalRandom.current();
double rand = random.nextDouble(1, 100);
if (rand <= 0.164) {
return DyeColor.PINK.getWoolData();
}
if (rand <= 15) {
return random.nextBoolean() ? DyeColor.BLACK.getWoolData() : random.nextBoolean() ? DyeColor.GRAY.getWoolData() : DyeColor.LIGHT_GRAY.getWoolData();
}
return DyeColor.WHITE.getWoolData();
}
/** {@inheritDoc} */
@Override public boolean test(Map<Object, Object> ctx) throws Exception {
ThreadLocalRandom rnd = ThreadLocalRandom.current();
IgniteCache<Integer, Object> cache = cacheForOperation(true);
if (rnd.nextBoolean()) {
double salary = rnd.nextDouble() * args.range() * 1000;
double maxSalary = salary + 1000;
Collection<Cache.Entry<Integer, Object>> entries = executeQuery(salary, maxSalary);
for (Cache.Entry<Integer, Object> entry : entries) {
Person p = (Person)entry.getValue();
if (p.getSalary() < salary || p.getSalary() > maxSalary)
throw new Exception("Invalid person retrieved [min=" + salary + ", max=" + maxSalary +
", person=" + p + ']');
}
qryCnt.getAndIncrement();
}
else {
int i = rnd.nextInt(args.range());
cache.put(i, new Person(i, "firstName" + i, "lastName" + i, i * 1000));
putCnt.getAndIncrement();
}
return true;
}
/** {@inheritDoc} */
@Override public boolean test(Map<Object, Object> ctx) throws Exception {
ThreadLocalRandom rnd = ThreadLocalRandom.current();
if (rnd.nextBoolean()) {
double salary = rnd.nextDouble() * args.range() * 1000;
double maxSalary = salary + 1000;
Collection<Cache.Entry<Integer, Object>> entries = executeQuery(salary, maxSalary);
for (Cache.Entry<Integer, Object> entry : entries) {
Object o = entry.getValue();
double s = o instanceof Person ? ((Person) o).getSalary() : ((BinaryObject) o).<Double>field("salary");
if (s < salary || s > maxSalary)
throw new Exception("Invalid person retrieved [min=" + salary + ", max=" + maxSalary +
", person=" + o + ']');
}
qryCnt.getAndIncrement();
}
else {
int i = rnd.nextInt(args.range());
cache.query(new SqlFieldsQuery("merge into Person(_key, id, firstName, lastName, salary) " +
"values (?, ?, ?, ?, ?)").setArgs(i, i, "firstName" + i, "lastName" + i, (double) i * 1000));
putCnt.getAndIncrement();
}
return true;
}
/**
* @return Random transaction type.
*/
protected TransactionConcurrency transactionConcurrency() {
if (MvccFeatureChecker.forcedMvcc())
return PESSIMISTIC;
ThreadLocalRandom random = ThreadLocalRandom.current();
return random.nextBoolean() ? OPTIMISTIC : PESSIMISTIC;
}
public static Booking newInstance() {
ThreadLocalRandom random = ThreadLocalRandom.current();
int randInt = random.nextInt();
Booking booking = new Booking();
booking.firstname = "firstname" + randInt;
booking.lastname = "lastname" + randInt;
booking.totalprice = randInt;
booking.depositpaid = random.nextBoolean();
booking.bookingdates = BookingDates.newInstance();
booking.additionalneeds = null;
return booking;
}
public static void main(String[] args) throws Exception
{
ThreadLocalRandom random = ThreadLocalRandom.current();
try (TestingServer server = new TestingServer())
{
try (CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new ExponentialBackoffRetry(1000, 3)))
{
client.start();
try (CuratorCache cache = CuratorCache.build(client, PATH))
{
// there are several ways to set a listener on a CuratorCache. You can watch for individual events
// or for all events. Here, we'll use the builder to log individual cache actions
CuratorCacheListener listener = CuratorCacheListener.builder()
.forCreates(node -> System.out.println(String.format("Node created: [%s]", node)))
.forChanges((oldNode, node) -> System.out.println(String.format("Node changed. Old: [%s] New: [%s]", oldNode, node)))
.forDeletes(oldNode -> System.out.println(String.format("Node deleted. Old value: [%s]", oldNode)))
.forInitialized(() -> System.out.println("Cache initialized"))
.build();
// register the listener
cache.listenable().addListener(listener);
// the cache must be started
cache.start();
// now randomly create/change/delete nodes
for ( int i = 0; i < 1000; ++i )
{
int depth = random.nextInt(1, 4);
String path = makeRandomPath(random, depth);
if ( random.nextBoolean() )
{
client.create().orSetData().creatingParentsIfNeeded().forPath(path, Long.toString(random.nextLong()).getBytes());
}
else
{
client.delete().quietly().deletingChildrenIfNeeded().forPath(path);
}
Thread.sleep(5);
}
}
}
}
}
/**
* Returns a new deque of given size containing consecutive
* Integers 0 ... n - 1.
*/
private static ArrayDeque<Integer> populatedDeque(int n) {
// Randomize various aspects of memory layout, including
// capacity slop and wraparound.
final ArrayDeque<Integer> q;
ThreadLocalRandom rnd = ThreadLocalRandom.current();
switch (rnd.nextInt(6)) {
case 0: q = new ArrayDeque<Integer>(); break;
case 1: q = new ArrayDeque<Integer>(0); break;
case 2: q = new ArrayDeque<Integer>(1); break;
case 3: q = new ArrayDeque<Integer>(Math.max(0, n - 1)); break;
case 4: q = new ArrayDeque<Integer>(n); break;
case 5: q = new ArrayDeque<Integer>(n + 1); break;
default: throw new AssertionError();
}
switch (rnd.nextInt(3)) {
case 0:
q.addFirst(42);
assertEquals((Integer) 42, q.removeLast());
break;
case 1:
q.addLast(42);
assertEquals((Integer) 42, q.removeFirst());
break;
case 2: /* do nothing */ break;
default: throw new AssertionError();
}
assertTrue(q.isEmpty());
if (rnd.nextBoolean())
for (int i = 0; i < n; i++)
assertTrue(q.offerLast((Integer) i));
else
for (int i = n; --i >= 0; )
q.addFirst((Integer) i);
assertEquals(n, q.size());
if (n > 0) {
assertFalse(q.isEmpty());
assertEquals((Integer) 0, q.peekFirst());
assertEquals((Integer) (n - 1), q.peekLast());
}
return q;
}
/**
* @throws Exception If failed.
*/
@Test
public void testRecoveryRandomPutRemove() throws Exception {
try {
pageSize = 1024;
extraCcfg = new CacheConfiguration(CACHE2_NAME);
extraCcfg.setAffinity(new RendezvousAffinityFunction(false, PARTS));
Ignite ignite = startGrid(0);
ignite.cluster().active(true);
GridCacheDatabaseSharedManager dbMgr = (GridCacheDatabaseSharedManager)((IgniteEx)ignite).context()
.cache().context().database();
dbMgr.enableCheckpoints(false).get();
IgniteCache<Integer, IndexedValue> cache1 = ignite.cache(CACHE_NAME);
IgniteCache<Object, Object> cache2 = ignite.cache(CACHE2_NAME);
final int KEYS1 = 100;
for (int i = 0; i < KEYS1; i++)
cache1.put(i, new IndexedValue(i));
for (int i = 0; i < KEYS1; i++) {
if (i % 2 == 0)
cache1.remove(i);
}
ThreadLocalRandom rnd = ThreadLocalRandom.current();
for (int i = 0; i < KEYS1; i++) {
cache2.put(i, new byte[rnd.nextInt(512)]);
if (rnd.nextBoolean())
cache2.put(i, new byte[rnd.nextInt(512)]);
if (rnd.nextBoolean())
cache2.remove(i);
}
ignite.close();
ignite = startGrid(0);
ignite.cluster().active(true);
ignite.cache(CACHE_NAME).put(1, new IndexedValue(0));
}
finally {
stopAllGrids();
}
}
/**
* @throws Exception If failed.
*/
@Test
public void testFreeListRecovery() throws Exception {
try {
pageSize = 1024;
extraCcfg = new CacheConfiguration(CACHE2_NAME);
Ignite ignite = startGrid(0);
ignite.cluster().active(true);
IgniteCache<Integer, IndexedValue> cache1 = ignite.cache(CACHE_NAME);
IgniteCache<Object, Object> cache2 = ignite.cache(CACHE2_NAME);
final int KEYS1 = 2048;
for (int i = 0; i < KEYS1; i++)
cache1.put(i, new IndexedValue(i));
for (int i = 0; i < KEYS1; i++) {
if (i % 2 == 0)
cache1.remove(i);
}
ThreadLocalRandom rnd = ThreadLocalRandom.current();
for (int i = 0; i < KEYS1; i++) {
cache2.put(i, new byte[rnd.nextInt(512)]);
if (rnd.nextBoolean())
cache2.put(i, new byte[rnd.nextInt(512)]);
if (rnd.nextBoolean())
cache2.remove(i);
}
Map<Integer, T2<Map<Integer, long[]>, int[]>> cache1_1 = getFreeListData(ignite, CACHE_NAME);
Map<Integer, T2<Map<Integer, long[]>, int[]>> cache2_1 = getFreeListData(ignite, CACHE2_NAME);
T2<long[], Integer> rl1_1 = getReuseListData(ignite, CACHE_NAME);
T2<long[], Integer> rl2_1 = getReuseListData(ignite, CACHE2_NAME);
ignite.close();
ignite = startGrid(0);
ignite.cluster().active(true);
cache1 = ignite.cache(CACHE_NAME);
cache2 = ignite.cache(CACHE2_NAME);
for (int i = 0; i < KEYS1; i++) {
cache1.get(i);
cache2.get(i);
}
Map<Integer, T2<Map<Integer, long[]>, int[]>> cache1_2 = getFreeListData(ignite, CACHE_NAME);
Map<Integer, T2<Map<Integer, long[]>, int[]>> cache2_2 = getFreeListData(ignite, CACHE2_NAME);
T2<long[], Integer> rl1_2 = getReuseListData(ignite, CACHE_NAME);
T2<long[], Integer> rl2_2 = getReuseListData(ignite, CACHE2_NAME);
checkEquals(cache1_1, cache1_2);
checkEquals(cache2_1, cache2_2);
checkEquals(rl1_1, rl1_2);
checkEquals(rl2_1, rl2_2);
}
finally {
stopAllGrids();
}
}