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

The following examples show how to use java.util.concurrent.ThreadLocalRandom#nextInt() . 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
/** {@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 2
Source Project: ignite   File: GridCacheStopSelfTest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * @param node Node.
 * @param cache Cache.
 */
@SuppressWarnings("unchecked")
private void cacheOperations(Ignite node, IgniteCache<Integer, Integer> cache) {
    ThreadLocalRandom rnd = ThreadLocalRandom.current();

    Integer key = rnd.nextInt(1000);

    cache.put(key, key);

    cache.get(key);

    if (cache.getConfiguration(CacheConfiguration.class).getAtomicityMode() != TRANSACTIONAL_SNAPSHOT) {
        try (Transaction tx = node.transactions().txStart(OPTIMISTIC, REPEATABLE_READ)) {
            cache.put(key, key);

            tx.commit();
        }
    }

    try (Transaction tx = node.transactions().txStart(PESSIMISTIC, REPEATABLE_READ)) {
        cache.put(key, key);

        tx.commit();
    }
}
 
Example 3
/**
 * Returns a new queue of given size containing consecutive
 * Integers 0 ... n - 1, with given capacity range and fairness.
 */
static ArrayBlockingQueue<Integer> populatedQueue(
    int size, int minCapacity, int maxCapacity, boolean fair) {
    ThreadLocalRandom rnd = ThreadLocalRandom.current();
    int capacity = rnd.nextInt(minCapacity, maxCapacity + 1);
    ArrayBlockingQueue<Integer> q = new ArrayBlockingQueue<>(capacity);
    assertTrue(q.isEmpty());
    // shuffle circular array elements so they wrap
    {
        int n = rnd.nextInt(capacity);
        for (int i = 0; i < n; i++) q.add(42);
        for (int i = 0; i < n; i++) q.remove();
    }
    for (int i = 0; i < size; i++)
        assertTrue(q.offer((Integer) i));
    assertEquals(size == 0, q.isEmpty());
    assertEquals(capacity - size, q.remainingCapacity());
    assertEquals(size, q.size());
    if (size > 0)
        assertEquals((Integer) 0, q.peek());
    return q;
}
 
Example 4
public void update(@HttpQueryParameter("queries") String queries, EntityManager entityManager,
		ObjectResponse<World[]> response) {
	ThreadLocalRandom random = ThreadLocalRandom.current();
	int count = getQueryCount(queries);
	int[] ids = new int[count];
	for (int i = 0; i < ids.length; i++) {
		ids[i] = random.nextInt(1, 10001);
	}
	Arrays.sort(ids);
	World[] worlds = new World[count];
	for (int i = 0; i < worlds.length; i++) {
		worlds[i] = entityManager.find(World.class, ids[i]);
		worlds[i].setRandomNumber(random.nextInt(1, 10001));
	}
	response.send(worlds);
}
 
Example 5
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 6
Source Project: j2objc   File: ThreadLocalRandomTest.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * nextInt(non-positive) throws IllegalArgumentException
 */
public void testNextIntBoundNonPositive() {
    ThreadLocalRandom rnd = ThreadLocalRandom.current();
    for (int bound : new int[] { 0, -17, Integer.MIN_VALUE }) {
        try {
            rnd.nextInt(bound);
            shouldThrow();
        } catch (IllegalArgumentException success) {}
    }
}
 
Example 7
Source Project: XSeries   File: XParticle.java    License: MIT License 5 votes vote down vote up
/**
 * Generate a random RGB color for particles.
 *
 * @return a random color.
 * @since 1.0.0
 */
public static Color randomColor() {
    ThreadLocalRandom gen = ThreadLocalRandom.current();
    int randR = gen.nextInt(0, 256);
    int randG = gen.nextInt(0, 256);
    int randB = gen.nextInt(0, 256);

    return Color.fromRGB(randR, randG, randB);
}
 
Example 8
/**
 * All elements removed in the middle of CONCURRENT traversal.
 */
public void testElementRemovalDuringTraversal() {
    Collection c = impl.emptyCollection();
    ThreadLocalRandom rnd = ThreadLocalRandom.current();
    int n = rnd.nextInt(6);
    ArrayList copy = new ArrayList();
    for (int i = 0; i < n; i++) {
        Object x = impl.makeElement(i);
        copy.add(x);
        c.add(x);
    }
    ArrayList iterated = new ArrayList();
    ArrayList spliterated = new ArrayList();
    Spliterator s = c.spliterator();
    Iterator it = c.iterator();
    for (int i = rnd.nextInt(n + 1); --i >= 0; ) {
        assertTrue(s.tryAdvance(spliterated::add));
        if (rnd.nextBoolean()) assertTrue(it.hasNext());
        iterated.add(it.next());
    }
    Consumer alwaysThrows = e -> { throw new AssertionError(); };
    if (s.hasCharacteristics(Spliterator.CONCURRENT)) {
        c.clear();          // TODO: many more removal methods
        if (testImplementationDetails
            && !(c instanceof java.util.concurrent.ArrayBlockingQueue)) {
            if (rnd.nextBoolean())
                assertFalse(s.tryAdvance(alwaysThrows));
            else
                s.forEachRemaining(alwaysThrows);
        }
        if (it.hasNext()) iterated.add(it.next());
        if (rnd.nextBoolean()) assertIteratorExhausted(it);
    }
    assertTrue(copy.containsAll(iterated));
    assertTrue(copy.containsAll(spliterated));
}
 
Example 9
/**
 * nextInt(least >= bound) throws IllegalArgumentException
 */
public void testNextIntBadBounds() {
    int[][] badBoundss = {
        { 17, 2 },
        { -42, -42 },
        { Integer.MAX_VALUE, Integer.MIN_VALUE },
    };
    ThreadLocalRandom rnd = ThreadLocalRandom.current();
    for (int[] badBounds : badBoundss) {
        try {
            rnd.nextInt(badBounds[0], badBounds[1]);
            shouldThrow();
        } catch (IllegalArgumentException success) {}
    }
}
 
Example 10
/** {@inheritDoc} */
@Override public Object load(Object key) throws CacheLoaderException {
    ThreadLocalRandom r = ThreadLocalRandom.current();

    if (r.nextInt() % 5 == 0)
        return new TestObject(PAGE_SIZE / 4 - 50 + r.nextInt(5000)); // Fragmented object.
    else
        return new TestObject(r.nextInt(PAGE_SIZE / 4 - 50)); // Fits in one page.
}
 
Example 11
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
}
 
Example 12
Source Project: Jupiter   File: RandomLoadBalancer.java    License: Apache License 2.0 5 votes vote down vote up
@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];
}
 
Example 13
private static SortedKafkaMessageBuffer<KafkaEventMessage> populatedBuffer(int size,
                                                                           int minCapacity,
                                                                           int maxCapacity) {
    SortedKafkaMessageBuffer<KafkaEventMessage> buff = null;
    try {
        ThreadLocalRandom rnd = ThreadLocalRandom.current();
        int capacity = rnd.nextInt(minCapacity, maxCapacity + 1);
        buff = new SortedKafkaMessageBuffer<>(capacity);
        assertTrue(buff.isEmpty());
        // shuffle circular array elements so they wrap
        {
            int n = rnd.nextInt(capacity);
            for (int i = 0; i < n; i++) {
                buff.put(message(42, 42, 42, "42"));
            }
            for (int i = 0; i < n; i++) {
                buff.poll(1, TimeUnit.NANOSECONDS);
            }
        }
        for (int i = 0; i < size; i++) {
            buff.put(message(i, i, i, "ma"));
        }
        assertEquals(size == 0, buff.isEmpty());
        assertEquals(capacity - size, buff.remainingCapacity());
        assertEquals(size, buff.size());
        if (size > 0) {
            assertThat(buff.peek()).isNotNull();
        }
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    return buff;
}
 
Example 14
Source Project: kafka-streams-ex   File: LogonGenerator.java    License: MIT License 5 votes vote down vote up
/** Simulates logon events. Writes to the "logons" topic. */
@Override
public void run() {
    
    ThreadLocalRandom rng = ThreadLocalRandom.current();
    
    while(true) {
        
        // Select a user.
        String user = users[rng.nextInt(users.length)];

        // Select an event.
        String event = events[rng.nextInt(events.length)];

        // Check the state of the user.
        String userState = loggedOn.get(user);

        // Emit the event if it's a new state.
        if((userState == null) || (userState != event)) {

            // Update the state.
            loggedOn.put(user, event);
            
            ProducerRecord<String, String> record = 
                new ProducerRecord<>("logons", user, event);

            producer.send(record);
        } // Close if statement on userState.

        try {
            Thread.sleep(500L);
        } catch (InterruptedException e) {
            ;
        } // Close try/catch on Thread.sleep.

    } // Close infinite loop.
}
 
Example 15
@Test
public void testIteratorWithRandomGraph() throws Exception
{
    Map<String, String> pathAndData = new HashMap<>();
    ThreadLocalRandom random = ThreadLocalRandom.current();
    int nodeQty = random.nextInt(100, 200);
    int maxPerRow = random.nextInt(1, 10);
    int maxDepth = random.nextInt(3, 5);
    try ( CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)) )
    {
        client.start();

        String basePath = "/base/test";
        try (TreeCache treeCache = new TreeCache(client, basePath) )
        {
            treeCache.start();

            client.create().creatingParentsIfNeeded().forPath(basePath, "0".getBytes());
            pathAndData.put(basePath, "0");

            while ( nodeQty-- > 0 )
            {
                int thisDepth = random.nextInt(1, maxDepth + 1);
                StringBuilder path = new StringBuilder(basePath);
                for ( int i = 0; i < thisDepth; ++i )
                {
                    path.append("/").append(random.nextInt(maxPerRow));
                    long value = random.nextLong();
                    pathAndData.put(path.toString(), Long.toString(value));
                    client.create().orSetData().forPath(path.toString(), Long.toString(value).getBytes());
                }
            }

            timing.sleepABit(); // let the cache settle

            Assert.assertEquals(treeCache.size(), pathAndData.size());

            // at this point we have a cached graph of random nodes with random values
            Iterator<ChildData> iterator = treeCache.iterator();
            while ( iterator.hasNext() )
            {
                ChildData next = iterator.next();
                Assert.assertTrue(pathAndData.containsKey(next.getPath()));
                Assert.assertEquals(pathAndData.get(next.getPath()).getBytes(), next.getData());
                pathAndData.remove(next.getPath());
            }

            Assert.assertEquals(pathAndData.size(), 0); // above loop should have removed all nodes
        }
    }
}
 
Example 16
@Test
public void testRemoveInsertMixKeepsOrder() {

	InternalPriorityQueue<TestElement> priorityQueue = newPriorityQueue(3);
	final Comparator<Long> comparator = getTestElementPriorityComparator();
	final ThreadLocalRandom random = ThreadLocalRandom.current();
	final int testSize = 300;
	final int addCounterMax = testSize / 4;
	int iterationsTillNextAdds = random.nextInt(addCounterMax);
	HashSet<TestElement> checkSet = new HashSet<>(testSize);

	insertRandomElements(priorityQueue, checkSet, testSize);

	// check that the whole set is still in order
	while (!checkSet.isEmpty()) {

		final long highestPrioValue = getHighestPriorityValueForComparator();

		Iterator<TestElement> iterator = checkSet.iterator();
		TestElement element = iterator.next();
		iterator.remove();

		final boolean removesHead = element.equals(priorityQueue.peek());

		if (removesHead) {
			Assert.assertTrue(priorityQueue.remove(element));
		} else {
			priorityQueue.remove(element);
		}

		long currentPriorityWatermark;

		// test some bulk polling from time to time
		if (removesHead) {
			currentPriorityWatermark = element.getPriority();
		} else {
			currentPriorityWatermark = highestPrioValue;
		}

		while ((element = priorityQueue.poll()) != null) {
			Assert.assertTrue(comparator.compare(element.getPriority(), currentPriorityWatermark) >= 0);
			currentPriorityWatermark = element.getPriority();
			if (--iterationsTillNextAdds == 0) {
				// some random adds
				iterationsTillNextAdds = random.nextInt(addCounterMax);
				insertRandomElements(priorityQueue, new HashSet<>(checkSet), 1 + random.nextInt(3));
				currentPriorityWatermark = priorityQueue.peek().getPriority();
			}
		}

		Assert.assertTrue(priorityQueue.isEmpty());

		priorityQueue.addAll(checkSet);
	}
}
 
Example 17
@Test
public void testRemoveInsertMixKeepsOrder() {

	InternalPriorityQueue<TestElement> priorityQueue = newPriorityQueue(3);
	final Comparator<Long> comparator = getTestElementPriorityComparator();
	final ThreadLocalRandom random = ThreadLocalRandom.current();
	final int testSize = 300;
	final int addCounterMax = testSize / 4;
	int iterationsTillNextAdds = random.nextInt(addCounterMax);
	HashSet<TestElement> checkSet = new HashSet<>(testSize);

	insertRandomElements(priorityQueue, checkSet, testSize);

	// check that the whole set is still in order
	while (!checkSet.isEmpty()) {

		final long highestPrioValue = getHighestPriorityValueForComparator();

		Iterator<TestElement> iterator = checkSet.iterator();
		TestElement element = iterator.next();
		iterator.remove();

		final boolean removesHead = element.equals(priorityQueue.peek());

		if (removesHead) {
			Assert.assertTrue(priorityQueue.remove(element));
		} else {
			priorityQueue.remove(element);
		}

		long currentPriorityWatermark;

		// test some bulk polling from time to time
		if (removesHead) {
			currentPriorityWatermark = element.getPriority();
		} else {
			currentPriorityWatermark = highestPrioValue;
		}

		while ((element = priorityQueue.poll()) != null) {
			Assert.assertTrue(comparator.compare(element.getPriority(), currentPriorityWatermark) >= 0);
			currentPriorityWatermark = element.getPriority();
			if (--iterationsTillNextAdds == 0) {
				// some random adds
				iterationsTillNextAdds = random.nextInt(addCounterMax);
				insertRandomElements(priorityQueue, new HashSet<>(checkSet), 1 + random.nextInt(3));
				currentPriorityWatermark = priorityQueue.peek().getPriority();
			}
		}

		Assert.assertTrue(priorityQueue.isEmpty());

		priorityQueue.addAll(checkSet);
	}
}
 
Example 18
/**
 * Various ways of traversing a collection yield same elements
 */
public void testTraversalEquivalence() {
    Collection c = impl.emptyCollection();
    ThreadLocalRandom rnd = ThreadLocalRandom.current();
    int n = rnd.nextInt(6);
    for (int i = 0; i < n; i++) c.add(impl.makeElement(i));
    ArrayList iterated = new ArrayList();
    ArrayList iteratedForEachRemaining = new ArrayList();
    ArrayList tryAdvanced = new ArrayList();
    ArrayList spliterated = new ArrayList();
    ArrayList splitonced = new ArrayList();
    ArrayList forEached = new ArrayList();
    ArrayList streamForEached = new ArrayList();
    ConcurrentLinkedQueue parallelStreamForEached = new ConcurrentLinkedQueue();
    ArrayList removeIfed = new ArrayList();
    for (Object x : c) iterated.add(x);
    c.iterator().forEachRemaining(iteratedForEachRemaining::add);
    for (Spliterator s = c.spliterator();
         s.tryAdvance(tryAdvanced::add); ) {}
    c.spliterator().forEachRemaining(spliterated::add);
    {                       // trySplit returns "strict prefix"
        Spliterator s1 = c.spliterator(), s2 = s1.trySplit();
        if (s2 != null) s2.forEachRemaining(splitonced::add);
        s1.forEachRemaining(splitonced::add);
    }
    c.forEach(forEached::add);
    c.stream().forEach(streamForEached::add);
    c.parallelStream().forEach(parallelStreamForEached::add);
    c.removeIf(e -> { removeIfed.add(e); return false; });
    boolean ordered =
        c.spliterator().hasCharacteristics(Spliterator.ORDERED);
    if (c instanceof List || c instanceof Deque)
        assertTrue(ordered);
    HashSet cset = new HashSet(c);
    assertEquals(cset, new HashSet(parallelStreamForEached));
    if (ordered) {
        assertEquals(iterated, iteratedForEachRemaining);
        assertEquals(iterated, tryAdvanced);
        assertEquals(iterated, spliterated);
        assertEquals(iterated, splitonced);
        assertEquals(iterated, forEached);
        assertEquals(iterated, streamForEached);
        assertEquals(iterated, removeIfed);
    } else {
        assertEquals(cset, new HashSet(iterated));
        assertEquals(cset, new HashSet(iteratedForEachRemaining));
        assertEquals(cset, new HashSet(tryAdvanced));
        assertEquals(cset, new HashSet(spliterated));
        assertEquals(cset, new HashSet(splitonced));
        assertEquals(cset, new HashSet(forEached));
        assertEquals(cset, new HashSet(streamForEached));
        assertEquals(cset, new HashSet(removeIfed));
    }
    if (c instanceof Deque) {
        Deque d = (Deque) c;
        ArrayList descending = new ArrayList();
        ArrayList descendingForEachRemaining = new ArrayList();
        for (Iterator it = d.descendingIterator(); it.hasNext(); )
            descending.add(it.next());
        d.descendingIterator().forEachRemaining(
            e -> descendingForEachRemaining.add(e));
        Collections.reverse(descending);
        Collections.reverse(descendingForEachRemaining);
        assertEquals(iterated, descending);
        assertEquals(iterated, descendingForEachRemaining);
    }
}
 
Example 19
void run() throws Throwable {
//         System.out.printf(
//             "iterations=%d size=%d, warmup=%1g, filter=\"%s\"%n",
//             iterations, size, warmupSeconds, filter);

        final ArrayList<Integer> al = new ArrayList<>(size);

        // Populate collections with random data
        final ThreadLocalRandom rnd = ThreadLocalRandom.current();
        for (int i = 0; i < size; i++)
            al.add(rnd.nextInt(size));

        final ArrayDeque<Integer> ad = new ArrayDeque<>(al);
        final ArrayBlockingQueue<Integer> abq = new ArrayBlockingQueue<>(al.size());
        abq.addAll(al);

        // shuffle circular array elements so they wrap
        for (int i = 0, n = rnd.nextInt(size); i < n; i++) {
            ad.addLast(ad.removeFirst());
            abq.add(abq.remove());
        }

        ArrayList<Job> jobs = new ArrayList<>(Arrays.asList());

        List.of(al, ad, abq,
                new LinkedList<>(al),
                new PriorityQueue<>(al),
                new Vector<>(al),
                new ConcurrentLinkedQueue<>(al),
                new ConcurrentLinkedDeque<>(al),
                new LinkedBlockingQueue<>(al),
                new LinkedBlockingDeque<>(al),
                new LinkedTransferQueue<>(al),
                new PriorityBlockingQueue<>(al))
            .stream()
            .forEach(x -> {
                         jobs.addAll(collectionJobs(x));
                         if (x instanceof Deque)
                             jobs.addAll(dequeJobs((Deque<Integer>)x));
                     });

        if (reverse) Collections.reverse(jobs);
        if (shuffle) Collections.shuffle(jobs);

        time(filter(filter, jobs));
    }
 
Example 20
/** */
@Test
public void testValidateIndexesFailedOnNotIdleCluster() throws Exception {
    checkpointFreq = 100L;

    Ignite ignite = prepareGridForTest();

    AtomicBoolean stopFlag = new AtomicBoolean();

    IgniteCache<Integer, GridCommandHandlerIndexingUtils.Person> cache = ignite.cache(CACHE_NAME);

    Thread loadThread = new Thread(() -> {
        ThreadLocalRandom rnd = ThreadLocalRandom.current();

        while (!stopFlag.get()) {
            int id = rnd.nextInt();

            cache.put(id, new GridCommandHandlerIndexingUtils.Person(id, "name" + id));

            if (Thread.interrupted())
                break;
        }
    });

    try {
        loadThread.start();

        doSleep(checkpointFreq);

        injectTestSystemOut();

        assertEquals(EXIT_CODE_OK, execute("--cache", "validate_indexes", "--check-crc", CACHE_NAME));
    }
    finally {
        stopFlag.set(true);

        loadThread.join();
    }

    String out = testOut.toString();

    assertContains(log, out, GRID_NOT_IDLE_MSG + "[\"" + GROUP_NAME + "\"]");
}