java.util.concurrent.ThreadLocalRandom#nextInt ( )源码实例Demo

下面列出了java.util.concurrent.ThreadLocalRandom#nextInt ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: ignite   文件: IgniteSqlDeleteFilteredBenchmark.java
/** {@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;
}
 
源代码2 项目: ignite   文件: GridCacheStopSelfTest.java
/**
 * @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();
    }
}
 
源代码3 项目: openjdk-jdk9   文件: ArrayBlockingQueueTest.java
/**
 * 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;
}
 
源代码4 项目: FrameworkBenchmarks   文件: Logic.java
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);
}
 
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());
	}
}
 
源代码6 项目: j2objc   文件: ThreadLocalRandomTest.java
/**
 * 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) {}
    }
}
 
源代码7 项目: XSeries   文件: XParticle.java
/**
 * 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);
}
 
源代码8 项目: openjdk-jdk9   文件: Collection8Test.java
/**
 * 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));
}
 
源代码9 项目: openjdk-jdk9   文件: ThreadLocalRandomTest.java
/**
 * 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) {}
    }
}
 
源代码10 项目: ignite   文件: PageEvictionReadThroughTest.java
/** {@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.
}
 
源代码11 项目: hazelcast-jet-training   文件: TradeSource.java
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
}
 
源代码12 项目: Jupiter   文件: RandomLoadBalancer.java
@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 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;
}
 
源代码14 项目: kafka-streams-ex   文件: LogonGenerator.java
/** 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.
}
 
源代码15 项目: curator   文件: TestTreeCacheIteratorAndSize.java
@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
        }
    }
}
 
源代码16 项目: flink   文件: InternalPriorityQueueTestBase.java
@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);
	}
}
 
@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);
	}
}
 
源代码18 项目: openjdk-jdk9   文件: Collection8Test.java
/**
 * 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);
    }
}
 
源代码19 项目: openjdk-jdk9   文件: IteratorMicroBenchmark.java
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));
    }
 
源代码20 项目: ignite   文件: GridCommandHandlerIndexingTest.java
/** */
@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 + "\"]");
}