Example usage for java.util.concurrent ThreadLocalRandom current

List of usage examples for java.util.concurrent ThreadLocalRandom current

Introduction

In this page you can find the example usage for java.util.concurrent ThreadLocalRandom current.

Prototype

public static ThreadLocalRandom current() 

Source Link

Document

Returns the current thread's ThreadLocalRandom .

Usage

From source file:io.prestosql.operator.aggregation.AbstractTestApproximateCountDistinct.java

@Test(dataProvider = "provideStandardErrors")
public void testMixedNullsAndNonNulls(double maxStandardError) {
    int uniques = getUniqueValuesCount();
    List<Object> baseline = createRandomSample(uniques, (int) (uniques * 1.5));

    // Randomly insert nulls
    // We need to retain the preexisting order to ensure that the HLL can generate the same estimates.
    Iterator<Object> iterator = baseline.iterator();
    List<Object> mixed = new ArrayList<>();
    while (iterator.hasNext()) {
        mixed.add(ThreadLocalRandom.current().nextBoolean() ? null : iterator.next());
    }//  w  w w .j  a va2  s  . co  m

    assertCount(mixed, maxStandardError, estimateGroupByCount(baseline, maxStandardError));
}

From source file:com.github.benmanes.caffeine.cache.Stresser.java

public void run() throws InterruptedException {
    ConcurrentTestHarness.timeTasks(operation.maxThreads, () -> {
        int index = ThreadLocalRandom.current().nextInt();
        for (;;) {
            Integer key = ints[index++ & MASK];
            switch (operation) {
            case READ:
                cache.getIfPresent(key);
                break;
            case WRITE:
                cache.put(key, key);/*from  w  w  w .j  a v a  2  s.c o m*/
                break;
            case REFRESH:
                cache.refresh(key);
                break;
            }
        }
    });
}

From source file:org.apache.jmeter.functions.RandomFromMultipleVars.java

/** {@inheritDoc} */
@Override//from  w w w  .ja  v a 2s  .  co  m
public String execute(SampleResult previousResult, Sampler currentSampler) throws InvalidVariableException {

    String variablesNamesSplitBySeparatorValue = variablesNamesSplitBySeparator.execute().trim();
    JMeterVariables vars = getVariables();
    String outputValue = "";
    String separator = "";
    if (vars != null) { // vars will be null on TestPlan
        List<String> results = new ArrayList<>();
        String[] variables = variablesNamesSplitBySeparatorValue.split(SEPARATOR);
        for (String varName : variables) {
            if (!StringUtils.isEmpty(varName)) {
                extractVariableValuesToList(varName, vars, results);
            }
        }

        if (results.size() > 0) {
            int randomIndex = ThreadLocalRandom.current().nextInt(0, results.size());
            outputValue = results.get(randomIndex);
        } else {
            if (log.isDebugEnabled()) {
                log.debug("RandomFromMultiResult didn't find <var>_matchNr in variables :'"
                        + variablesNamesSplitBySeparatorValue + "' using separator:'" + separator
                        + "', will return empty value");
            }
        }

        if (varName != null) {
            final String varTrim = varName.execute().trim();
            if (varTrim.length() > 0) {
                vars.put(varTrim, outputValue);
            }
        }
    }
    return outputValue;

}

From source file:org.apache.hadoop.hbase.io.asyncfs.TestFanOutOneBlockAsyncDFSOutput.java

static void writeAndVerify(EventLoop eventLoop, DistributedFileSystem dfs, Path f,
        final FanOutOneBlockAsyncDFSOutput out) throws IOException, InterruptedException, ExecutionException {
    final byte[] b = new byte[10];
    ThreadLocalRandom.current().nextBytes(b);
    final FanOutOneBlockAsyncDFSOutputFlushHandler handler = new FanOutOneBlockAsyncDFSOutputFlushHandler();
    eventLoop.execute(new Runnable() {

        @Override//from ww w.j  a v a  2s .  c om
        public void run() {
            out.write(b, 0, b.length);
            out.flush(null, handler, false);
        }
    });
    assertEquals(b.length, handler.get());
    out.close();
    assertEquals(b.length, dfs.getFileStatus(f).getLen());
    byte[] actual = new byte[b.length];
    try (FSDataInputStream in = dfs.open(f)) {
        in.readFully(actual);
    }
    assertArrayEquals(b, actual);
}

From source file:ffx.algorithms.mc.BoltzmannMC.java

/**
 * Criterion for accept/reject a move; intended to be used mostly internally.
 * @param e1 Initial energy//from  w  w w.  j a v  a  2  s  .co m
 * @param e2 Final energy
 * @return If move accepted
 */
@Override
public boolean evaluateMove(double e1, double e2) {
    if (e2 <= e1) {
        return true;
    } else {
        // p(X) = exp(-U(X)/kb*T)
        double prob = FastMath.exp(kbTinv * (e2 - e1));

        assert (prob >= 0.0 && prob <= 1.0) : "Probability of a Monte Carlo move up in energy should be 0-1";

        double trial = ThreadLocalRandom.current().nextDouble();
        return (trial <= prob);
    }
}

From source file:ubicrypt.core.TestUtils.java

/**
 * Returns a free port number on localhost.
 *
 * <p>Heavily inspired from org.eclipse.jdt.launching.SocketUtil (to avoid a dependency to JDT
 * just because of this). Slightly improved with stop() missing in JDT. And throws exception
 * instead of returning -1.//from w ww  .j a  va2s .  com
 *
 * @return a free port number on localhost
 * @throws IllegalStateException if unable to find a free port
 */
public static int findFreePort() {
    ServerSocket socket = null;
    do {
        try {
            final int port = ThreadLocalRandom.current().nextInt(49152, 65535 + 1);
            socket = new ServerSocket(port);
            socket.setReuseAddress(false);
            try {
                socket.close();
            } catch (final IOException e) {
                // Ignore IOException on stop()
            }
            return port;
        } catch (final IOException e) {
        } finally {
            if (socket != null) {
                try {
                    socket.close();
                } catch (final IOException e) {
                }
            }
        }
    } while (true);
}

From source file:org.lambda3.indra.service.mock.MockedNeighborsResourceImpl.java

@Override
public NeighborRelatednessResponse getNeighborRelatedness(NeighborRelatednessRequest request) {
    Map<String, Map<String, Double>> terms = new HashMap<>();

    for (String term : request.getTerms()) {
        Map<String, Double> ns = new HashMap<>();
        for (String neighbor : getRandomWords()) {
            ns.put(neighbor, ThreadLocalRandom.current().nextDouble(0, 1));
        }/*from   ww w  . j a  va  2 s. c o m*/

        terms.put(term, ns);
    }

    return new NeighborRelatednessResponse(request, terms);
}

From source file:com.github.jinahya.codec.BossVsEngineerTestNanoTimeDecode.java

@Test
public void testDecode() {

    final double[] elapsedLikeABoss = new double[ROUNDS];
    final double[] elapsedLikeAnEngineer = new double[ROUNDS];

    for (int i = 0; i < ROUNDS; i++) {
        final byte[] encoded = Tests.encodedBytes();
        if (ThreadLocalRandom.current().nextBoolean()) {
            elapsedLikeABoss[i] = decodeLikeABoss(encoded);
            elapsedLikeAnEngineer[i] = decodeLikeAnEngineer(encoded);
        } else {//from   w w  w  . ja va  2 s.com
            elapsedLikeAnEngineer[i] = decodeLikeAnEngineer(encoded);
            elapsedLikeABoss[i] = decodeLikeABoss(encoded);
        }
    }

    LOGGER.log(Level.INFO, "elapsed.like.a.boss: {0} [{1}, {2}, {3}, ..., {4}, {5}, {6}]", new Object[] {
            StatUtils.mean(elapsedLikeABoss, 1, elapsedLikeABoss.length - 1), elapsedLikeABoss[0],
            elapsedLikeABoss[1], elapsedLikeABoss[2], elapsedLikeABoss[elapsedLikeABoss.length - 3],
            elapsedLikeABoss[elapsedLikeABoss.length - 2], elapsedLikeABoss[elapsedLikeABoss.length - 1] });

    LOGGER.log(Level.INFO, "elapsed.like.an.engineer: {0} [{1}, {2}, {3}, ..., {4}, {5}, {6}]",
            new Object[] { StatUtils.mean(elapsedLikeAnEngineer, 1, elapsedLikeAnEngineer.length - 1),
                    elapsedLikeAnEngineer[0], elapsedLikeAnEngineer[1], elapsedLikeAnEngineer[2],
                    elapsedLikeAnEngineer[elapsedLikeAnEngineer.length - 3],
                    elapsedLikeAnEngineer[elapsedLikeAnEngineer.length - 2],
                    elapsedLikeAnEngineer[elapsedLikeAnEngineer.length - 1] });
}

From source file:com.github.jinahya.codec.BossVsEngineerTestNanoTimeEncode.java

@Test
public void testEncode() {

    final double[] elapsedLikeABoss = new double[ROUNDS];
    final double[] elapsedLikeAnEngineer = new double[ROUNDS];

    for (int i = 0; i < ROUNDS; i++) {
        final byte[] decoded = Tests.decodedBytes();
        if (ThreadLocalRandom.current().nextBoolean()) {
            elapsedLikeABoss[i] = encodeLikeABoss(decoded);
            elapsedLikeAnEngineer[i] = encodeLikeAnEngineer(decoded);
        } else {/*from w w w . j  av  a 2s .  c  om*/
            elapsedLikeAnEngineer[i] = encodeLikeAnEngineer(decoded);
            elapsedLikeABoss[i] = encodeLikeABoss(decoded);
        }
    }

    LOGGER.log(Level.INFO, "elapsed.like.a.boss: {0} [{1}, {2}, {3}, ..., {4}, {5}, {6}]", new Object[] {
            StatUtils.mean(elapsedLikeABoss, 1, elapsedLikeABoss.length - 1), elapsedLikeABoss[0],
            elapsedLikeABoss[1], elapsedLikeABoss[2], elapsedLikeABoss[elapsedLikeABoss.length - 3],
            elapsedLikeABoss[elapsedLikeABoss.length - 2], elapsedLikeABoss[elapsedLikeABoss.length - 1] });

    LOGGER.log(Level.INFO, "elapsed.like.an.engineer: {0} [{1}, {2}, {3}, ..., {4}, {5}, {6}]",
            new Object[] { StatUtils.mean(elapsedLikeAnEngineer, 1, elapsedLikeAnEngineer.length - 1),
                    elapsedLikeAnEngineer[0], elapsedLikeAnEngineer[1], elapsedLikeAnEngineer[2],
                    elapsedLikeAnEngineer[elapsedLikeAnEngineer.length - 3],
                    elapsedLikeAnEngineer[elapsedLikeAnEngineer.length - 2],
                    elapsedLikeAnEngineer[elapsedLikeAnEngineer.length - 1] });
}

From source file:com.adaptris.core.services.WaitService.java

protected long waitMs() {
    long maxWaitMs = TimeInterval.toMillisecondsDefaultIfNull(getWaitInterval(), DEFAULT_WAIT);
    return randomizeWait() ? ThreadLocalRandom.current().nextLong(maxWaitMs) : maxWaitMs;
}