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

The following examples show how to use java.util.concurrent.ThreadLocalRandom#nextBoolean() . These examples are extracted from open source projects. 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
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();
      }
    }
  };
}
 
Example 2
/**
 * 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);
    }
}
 
Example 3
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();
      }
    }
  };
}
 
Example 4
/** {@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;
}
 
Example 5
/** {@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;
}
 
Example 6
/**
 * 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);
    }
}
 
Example 7
Source Project: flink   File: SkipListUtilsTest.java    License: 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 8
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);
}
 
Example 9
Source Project: Exam-Online   File: CaptchaUtils.java    License: Apache License 2.0 5 votes vote down vote up
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);
            }
        }
    }
}
 
Example 10
Source Project: ForgeHax   File: FancyChat.java    License: MIT License 5 votes vote down vote up
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);
}
 
Example 11
Source Project: Nukkit   File: EntitySheep.java    License: GNU General Public License v3.0 5 votes vote down vote up
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();
}
 
Example 12
Source Project: Nukkit   File: EntitySheep.java    License: GNU General Public License v3.0 5 votes vote down vote up
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();
}
 
Example 13
/** {@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;
}
 
Example 14
/** {@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;
}
 
Example 15
/**
 * @return Random transaction type.
 */
protected TransactionConcurrency transactionConcurrency() {
    if (MvccFeatureChecker.forcedMvcc())
        return PESSIMISTIC;

    ThreadLocalRandom random = ThreadLocalRandom.current();

    return random.nextBoolean() ? OPTIMISTIC : PESSIMISTIC;
}
 
Example 16
Source Project: frameworkium-core   File: Booking.java    License: Apache License 2.0 5 votes vote down vote up
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;
}
 
Example 17
Source Project: curator   File: CuratorCacheExample.java    License: Apache License 2.0 4 votes vote down vote up
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);
                }
            }
        }
    }
}
 
Example 18
/**
 * 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;
}
 
Example 19
/**
 * @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();
    }
}
 
Example 20
/**
 * @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();
    }
}