Search in sources :

Example 21 with ThreadLocalRandom

use of java.util.concurrent.ThreadLocalRandom in project quasar by puniverse.

the class DelayQueueBenchmark method performanceRun.

private static void performanceRun(final int runNumber, final Queue<DelayedValue> queue) throws Exception {
    final long start = System.nanoTime();
    final int repetitions = (REPETITIONS / NUM_PRODUCERS) * NUM_PRODUCERS;
    final Thread[] producers = new Thread[NUM_PRODUCERS];
    for (int t = 0; t < NUM_PRODUCERS; t++) {
        producers[t] = new Thread(new Runnable() {

            @Override
            public void run() {
                final ThreadLocalRandom rand = ThreadLocalRandom.current();
                int i = REPETITIONS / NUM_PRODUCERS;
                do {
                    while (!queue.offer(DelayedValue.instance(SEQUENCED, TEST_VALUE, rand.nextInt(0, 11)))) Thread.yield();
                } while (0 != --i);
            }
        });
    }
    for (int t = 0; t < NUM_PRODUCERS; t++) producers[t].start();
    DelayedValue result;
    int i = repetitions;
    do {
        while (null == (result = queue.poll())) Thread.yield();
    } while (0 != --i);
    for (int t = 0; t < NUM_PRODUCERS; t++) producers[t].join();
    final long duration = System.nanoTime() - start;
    final long ops = (repetitions * TimeUnit.SECONDS.toNanos(1)) / duration;
    System.out.format("%d - ops/sec=%,d - %s result=%s\n", Integer.valueOf(runNumber), Long.valueOf(ops), queue.getClass().getSimpleName(), result);
}
Also used : ThreadLocalRandom(java.util.concurrent.ThreadLocalRandom)

Example 22 with ThreadLocalRandom

use of java.util.concurrent.ThreadLocalRandom in project quasar by puniverse.

the class TransferChannel method awaitMatch.

/**
     * Spins/yields/blocks until node s is matched or caller gives up.
     *
     * @param s     the waiting node
     * @param pred  the predecessor of s, or s itself if it has no
     *              predecessor, or null if unknown (the null case does not occur
     *              in any current calls but may in possible future extensions)
     * @param e     the comparison value for checking match
     * @param timed if true, wait only until timeout elapses
     * @param nanos timeout in nanosecs, used only if timed is true
     * @return matched item, or e if unmatched on interrupt or timeout
     */
private Message awaitMatch(Node s, Node pred, Message e, boolean timed, long nanos) throws SuspendExecution {
    long lastTime = timed ? System.nanoTime() : 0L;
    Strand w = Strand.currentStrand();
    // no spins in fiber; otherwise, initialized after first item and cancel checks
    int spins = (w.isFiber() ? 0 : -1);
    // bound if needed
    ThreadLocalRandom randomYields = null;
    if (spins == 0)
        requestUnpark(s, w);
    for (; ; ) {
        Object item = s.item;
        if (item == CHANNEL_CLOSED)
            setReceiveClosed();
        if (item != e) {
            // matched
            // assert item != s;
            // avoid garbage
            s.forgetContents();
            return this.<Message>cast(item);
        }
        if ((w.isInterrupted() || (timed && nanos <= 0)) && s.casItem(e, s)) {
            // cancel
            unsplice(pred, s);
            return e;
        }
        if (spins < 0) {
            // establish spins at/near front
            if ((spins = spinsFor(pred, s.isData)) > 0)
                randomYields = ThreadLocalRandom.current();
        } else if (spins > 0) {
            // spin
            --spins;
            if (randomYields.nextInt(CHAINED_SPINS) == 0)
                // occasionally yield
                Strand.yield();
        } else if (s.waiter == null) {
            // request unpark then recheck
            requestUnpark(s, w);
        } else if (timed) {
            long now = System.nanoTime();
            if ((nanos -= now - lastTime) > 0)
                Strand.parkNanos(this, nanos);
            lastTime = now;
        } else {
            Strand.park(this);
        }
    }
}
Also used : ThreadLocalRandom(java.util.concurrent.ThreadLocalRandom) Strand(co.paralleluniverse.strands.Strand)

Example 23 with ThreadLocalRandom

use of java.util.concurrent.ThreadLocalRandom in project cassandra by apache.

the class LongBTreeTest method testRandomRangeAndBatches.

@Test
public void testRandomRangeAndBatches() throws ExecutionException, InterruptedException {
    ThreadLocalRandom random = ThreadLocalRandom.current();
    int treeSize = random.nextInt(maxTreeSize / 10, maxTreeSize * 10);
    for (int i = 0; i < perThreadTrees / 10; i++) testInsertions(threads * 10, treeSize, random.nextInt(1, 100) / 10f, treeSize / 100, true);
}
Also used : ThreadLocalRandom(java.util.concurrent.ThreadLocalRandom) Test(org.junit.Test)

Example 24 with ThreadLocalRandom

use of java.util.concurrent.ThreadLocalRandom in project cassandra by apache.

the class LongBTreeTest method randomKeys.

// select a random subset of the keys, with an optional random population of keys inbetween those that are present
// return a value with the search position
private static List<Integer> randomKeys(Iterable<Integer> canonical, boolean mixInNotPresentItems) {
    ThreadLocalRandom rnd = ThreadLocalRandom.current();
    boolean useFake = mixInNotPresentItems && rnd.nextBoolean();
    final float fakeRatio = rnd.nextFloat();
    List<Integer> results = new ArrayList<>();
    Long fakeLb = (long) Integer.MIN_VALUE, fakeUb = null;
    Integer max = null;
    for (Integer v : canonical) {
        if (!useFake || (fakeUb == null ? v - 1 : fakeUb) <= fakeLb + 1 || rnd.nextFloat() < fakeRatio) {
            // if we cannot safely construct a fake value, or our randomizer says not to, we emit the next real value
            results.add(v);
            fakeLb = v.longValue();
            fakeUb = null;
        } else {
            // exceeding the real value that would have proceeded (ignoring any other suppressed real values since)
            if (fakeUb == null)
                fakeUb = v.longValue() - 1;
            long mid = (fakeLb + fakeUb) / 2;
            assert mid < fakeUb;
            results.add((int) mid);
            fakeLb = mid;
        }
        max = v;
    }
    if (useFake && max != null && max < Integer.MAX_VALUE)
        results.add(max + 1);
    final float useChance = rnd.nextFloat();
    return Lists.newArrayList(filter(results, (x) -> rnd.nextFloat() < useChance));
}
Also used : java.util(java.util) ListenableFuture(com.google.common.util.concurrent.ListenableFuture) Iterables.transform(com.google.common.collect.Iterables.transform) Comparator.naturalOrder(java.util.Comparator.naturalOrder) Callable(java.util.concurrent.Callable) Predicates.notNull(com.google.common.base.Predicates.notNull) BTree.iterable(org.apache.cassandra.utils.btree.BTree.iterable) Lists(com.google.common.collect.Lists) ListenableFutureTask(com.google.common.util.concurrent.ListenableFutureTask) ThreadLocalRandom(java.util.concurrent.ThreadLocalRandom) Method(java.lang.reflect.Method) org.apache.cassandra.utils.btree(org.apache.cassandra.utils.btree) ExecutorService(java.util.concurrent.ExecutorService) Function(com.google.common.base.Function) MetricRegistry(com.codahale.metrics.MetricRegistry) Assert.assertTrue(org.junit.Assert.assertTrue) Test(org.junit.Test) Executors(java.util.concurrent.Executors) Snapshot(com.codahale.metrics.Snapshot) InvocationTargetException(java.lang.reflect.InvocationTargetException) ExecutionException(java.util.concurrent.ExecutionException) TimeUnit(java.util.concurrent.TimeUnit) Consumer(java.util.function.Consumer) CountDownLatch(java.util.concurrent.CountDownLatch) AtomicLong(java.util.concurrent.atomic.AtomicLong) Futures(com.google.common.util.concurrent.Futures) NamedThreadFactory(org.apache.cassandra.concurrent.NamedThreadFactory) Annotation(java.lang.annotation.Annotation) Timer(com.codahale.metrics.Timer) Comparator.reverseOrder(java.util.Comparator.reverseOrder) Iterables.filter(com.google.common.collect.Iterables.filter) Assert(org.junit.Assert) AtomicLong(java.util.concurrent.atomic.AtomicLong) ThreadLocalRandom(java.util.concurrent.ThreadLocalRandom)

Example 25 with ThreadLocalRandom

use of java.util.concurrent.ThreadLocalRandom in project cassandra by apache.

the class LongBTreeTest method randomTreeByUpdate.

private static RandomTree randomTreeByUpdate(int minSize, int maxSize) {
    assert minSize > 3;
    TreeSet<Integer> canonical = new TreeSet<>();
    ThreadLocalRandom random = ThreadLocalRandom.current();
    int targetSize = random.nextInt(minSize, maxSize);
    int maxModificationSize = random.nextInt(2, targetSize);
    Object[] accmumulate = BTree.empty();
    int curSize = 0;
    while (curSize < targetSize) {
        int nextSize = maxModificationSize == 1 ? 1 : random.nextInt(1, maxModificationSize);
        TreeSet<Integer> build = new TreeSet<>();
        for (int i = 0; i < nextSize; i++) {
            Integer next = random.nextInt();
            build.add(next);
            canonical.add(next);
        }
        accmumulate = BTree.update(accmumulate, naturalOrder(), build, UpdateFunction.<Integer>noOp());
        curSize += nextSize;
        maxModificationSize = Math.min(maxModificationSize, targetSize - curSize);
    }
    return new RandomTree(canonical, BTreeSet.<Integer>wrap(accmumulate, naturalOrder()));
}
Also used : ThreadLocalRandom(java.util.concurrent.ThreadLocalRandom)

Aggregations

ThreadLocalRandom (java.util.concurrent.ThreadLocalRandom)186 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)49 Ignite (org.apache.ignite.Ignite)47 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)45 IgniteCache (org.apache.ignite.IgniteCache)33 Test (org.junit.Test)28 ArrayList (java.util.ArrayList)26 IgniteException (org.apache.ignite.IgniteException)26 Transaction (org.apache.ignite.transactions.Transaction)24 CacheException (javax.cache.CacheException)21 HashMap (java.util.HashMap)16 Map (java.util.Map)15 IgniteTransactions (org.apache.ignite.IgniteTransactions)13 CountDownLatch (java.util.concurrent.CountDownLatch)12 TreeMap (java.util.TreeMap)11 Callable (java.util.concurrent.Callable)11 CacheConfiguration (org.apache.ignite.configuration.CacheConfiguration)10 AtomicLong (java.util.concurrent.atomic.AtomicLong)9 LongAdder (java.util.concurrent.atomic.LongAdder)9 ContinuousQuery (org.apache.ignite.cache.query.ContinuousQuery)9