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:org.apache.hadoop.hbase.client.TestAsyncNonMetaRegionLocator.java

@Test
public void testSingleRegionTable() throws IOException, InterruptedException, ExecutionException {
    createSingleRegionTable();/*from   w  ww .j ava2s.  c o  m*/
    ServerName serverName = TEST_UTIL.getRSForFirstRegionInTable(TABLE_NAME).getServerName();
    for (RegionLocateType locateType : RegionLocateType.values()) {
        assertLocEquals(EMPTY_START_ROW, EMPTY_END_ROW, serverName,
                LOCATOR.getRegionLocation(TABLE_NAME, EMPTY_START_ROW, locateType).get());
    }
    byte[] randKey = new byte[ThreadLocalRandom.current().nextInt(128)];
    ThreadLocalRandom.current().nextBytes(randKey);
    for (RegionLocateType locateType : RegionLocateType.values()) {
        assertLocEquals(EMPTY_START_ROW, EMPTY_END_ROW, serverName,
                LOCATOR.getRegionLocation(TABLE_NAME, randKey, locateType).get());
    }
}

From source file:learn.jersey.services.MultiThreadedClientExample.java

@Override
public int run(String[] args) throws Exception {

    if (args.length < 1 || args.length > 2) {
        System.out.println("Usage: " + this.getClass().getName() + " tableName [num_operations]");
        return -1;
    }/*from   www  . j  a  v  a  2 s  .  com*/

    final TableName tableName = TableName.valueOf(args[0]);
    int numOperations = DEFAULT_NUM_OPERATIONS;

    // the second arg is the number of operations to send.
    if (args.length == 2) {
        numOperations = Integer.parseInt(args[1]);
    }

    // Threads for the client only.
    //
    // We don't want to mix hbase and business logic.
    //
    ExecutorService service = new ForkJoinPool(threads * 2);

    // Create two different connections showing how it's possible to
    // separate different types of requests onto different connections
    final Connection writeConnection = ConnectionFactory.createConnection(getConf(), service);
    final Connection readConnection = ConnectionFactory.createConnection(getConf(), service);

    // At this point the entire cache for the region locations is full.
    // Only do this if the number of regions in a table is easy to fit into
    // memory.
    //
    // If you are interacting with more than 25k regions on a client then
    // it's probably not good
    // to do this at all.
    warmUpConnectionCache(readConnection, tableName);
    warmUpConnectionCache(writeConnection, tableName);

    List<Future<Boolean>> futures = new ArrayList<>(numOperations);
    for (int i = 0; i < numOperations; i++) {
        double r = ThreadLocalRandom.current().nextDouble();
        Future<Boolean> f;

        // For the sake of generating some synthetic load this queues
        // some different callables.
        // These callables are meant to represent real work done by your
        // application.
        if (r < .30) {
            f = internalPool.submit(new WriteExampleCallable(writeConnection, tableName));
        } else if (r < .50) {
            f = internalPool.submit(new SingleWriteExampleCallable(writeConnection, tableName));
        } else {
            f = internalPool.submit(new ReadExampleCallable(writeConnection, tableName));
        }
        futures.add(f);
    }

    // Wait a long time for all the reads/writes to complete
    for (Future<Boolean> f : futures) {
        f.get(10, TimeUnit.MINUTES);
    }

    // Clean up after our selves for cleanliness
    internalPool.shutdownNow();
    service.shutdownNow();
    return 0;
}

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

/**
 * Does all the work for a move./*from  w  w  w  .j av a2 s  .c  o m*/
 * Moveset is a continuous 360 degree spin of the chi[0] torsion.
 * U_or in Frenkel's notation (uDep here) is the associated torsion energy.
 * Evaluation criterion: P_accept = Min( 1, (Wn/Wo)*exp(-beta(U[n]-U[o]) )
 */
private boolean mcStep() {
    numMovesProposed++;
    boolean accepted;

    // Select a target residue.
    int which = ThreadLocalRandom.current().nextInt(targets.size());
    Residue target = targets.get(which);
    ResidueState origState = target.storeState();
    List<ROLS> chiList = target.getTorsionList();
    Torsion chi0 = getChiZeroTorsion(target);
    writeSnapshot("orig");

    /* Create old and new trial sets, calculate Wn and Wo, and choose a move bn.
    When doing strictly chi[0] moves, Frenkel/Smit's 'old' and 'new' configurations
    are the same state. The distinction is made here only to aid in future generalization.
    */
    List<MCMove> oldTrialSet = createTrialSet(target, origState, trialSetSize - 1);
    List<MCMove> newTrialSet = createTrialSet(target, origState, trialSetSize);
    report = new StringBuilder();
    report.append(String.format(" Rosenbluth Rotamer MC Move: %4d\n", numMovesProposed));
    report.append(String.format("    residue:   %s\n", target.toString()));
    report.append(String.format("    chi0:      %s\n", chi0.toString()));
    MCMove proposal = calculateRosenbluthFactors(target, chi0, origState, oldTrialSet, origState, newTrialSet);

    /* Calculate the independent portion of the total old-conf energy.
    Then apply the move and calculate the independent total new-conf energy.
    */
    setState(target, origState);
    writeSnapshot("uIndO");
    double uIndO = getTotalEnergy() - getTorsionEnergy(chi0);
    proposal.move();
    writeSnapshot("uIndN");
    double uIndN = getTotalEnergy() - getTorsionEnergy(chi0);

    // Apply acceptance criterion.
    double temperature = thermostat.getCurrentTemperature();
    double beta = 1.0 / (BOLTZMANN * temperature);
    double dInd = uIndN - uIndO;
    double dIndE = FastMath.exp(-beta * dInd);
    double criterion = (Wn / Wo) * FastMath.exp(-beta * (uIndN - uIndO));
    double metropolis = Math.min(1, criterion);
    double rng = ThreadLocalRandom.current().nextDouble();

    report.append(String.format("    theta:     %3.2f\n", ((RosenbluthChi0Move) proposal).theta));
    report.append(String.format("    criterion: %1.4f\n", criterion));
    report.append(String.format("       Wn/Wo:     %.2f\n", Wn / Wo));
    report.append(String.format("       uIndN,O:  %7.2f\t%7.2f\n", uIndN, uIndO));
    report.append(String.format("       dInd(E):  %7.2f\t%7.2f\n", dInd, dIndE));
    report.append(String.format("    rng:       %1.4f\n", rng));
    if (rng < metropolis) {
        numMovesAccepted++;
        report.append(String.format(" Accepted.\n"));
        accepted = true;
    } else {
        proposal.revertMove();
        report.append(String.format(" Denied.\n"));
        accepted = false;
    }
    logger.info(report.toString());

    // Cleanup.
    Wn = 0.0;
    Wo = 0.0;
    return accepted;
}

From source file:org.apache.hadoop.hbase.client.example.MultiThreadedClientExample.java

@Override
public int run(String[] args) throws Exception {

    if (args.length < 1 || args.length > 2) {
        System.out.println("Usage: " + this.getClass().getName() + " tableName [num_operations]");
        return -1;
    }/* w  ww.  j a v  a  2 s.  c o  m*/

    final TableName tableName = TableName.valueOf(args[0]);
    int numOperations = DEFAULT_NUM_OPERATIONS;

    // the second arg is the number of operations to send.
    if (args.length == 2) {
        numOperations = Integer.parseInt(args[1]);
    }

    // Threads for the client only.
    //
    // We don't want to mix hbase and business logic.
    //
    ExecutorService service = new ForkJoinPool(threads * 2);

    // Create two different connections showing how it's possible to
    // separate different types of requests onto different connections
    final Connection writeConnection = ConnectionFactory.createConnection(getConf(), service);
    final Connection readConnection = ConnectionFactory.createConnection(getConf(), service);

    // At this point the entire cache for the region locations is full.
    // Only do this if the number of regions in a table is easy to fit into memory.
    //
    // If you are interacting with more than 25k regions on a client then it's probably not good
    // to do this at all.
    warmUpConnectionCache(readConnection, tableName);
    warmUpConnectionCache(writeConnection, tableName);

    List<Future<Boolean>> futures = new ArrayList<>(numOperations);
    for (int i = 0; i < numOperations; i++) {
        double r = ThreadLocalRandom.current().nextDouble();
        Future<Boolean> f;

        // For the sake of generating some synthetic load this queues
        // some different callables.
        // These callables are meant to represent real work done by your application.
        if (r < .30) {
            f = internalPool.submit(new WriteExampleCallable(writeConnection, tableName));
        } else if (r < .50) {
            f = internalPool.submit(new SingleWriteExampleCallable(writeConnection, tableName));
        } else {
            f = internalPool.submit(new ReadExampleCallable(writeConnection, tableName));
        }
        futures.add(f);
    }

    // Wait a long time for all the reads/writes to complete
    for (Future<Boolean> f : futures) {
        f.get(10, TimeUnit.MINUTES);
    }

    // Clean up after our selves for cleanliness
    internalPool.shutdownNow();
    service.shutdownNow();
    return 0;
}

From source file:com.tesora.dve.sql.transform.strategy.SessionRewriteTransformFactory.java

private void rewriteRandFunctionCall(final RandFunctionCall rand) {
    if (rand.hasSeed()) {
        rand.setSeed(new ActualLiteralExpression(rand.getSeed(), TokenTypes.Signed_Integer,
                rand.getSeed().getSourceLocation(), null));
    } else {//w ww .  j  a  v  a2  s . co  m
        rand.setSeed(LiteralExpression.makeSignedIntegerLiteral(ThreadLocalRandom.current().nextInt()));
    }
}

From source file:org.apache.bookkeeper.common.util.TestBackoff.java

@Test
public void testDecorrelatedJittered() throws Exception {
    long startMs = ThreadLocalRandom.current().nextLong(1L, 1000L);
    long maxMs = ThreadLocalRandom.current().nextLong(startMs, startMs * 2);
    Stream<Long> backoffs = Backoff.decorrelatedJittered(startMs, maxMs).limit(10);
    Iterator<Long> backoffIter = backoffs.iterator();
    assertTrue(backoffIter.hasNext());/* w  w w.ja  va  2s  . c  o m*/
    assertEquals(startMs, backoffIter.next().longValue());
    AtomicLong prevMs = new AtomicLong(startMs);
    backoffIter.forEachRemaining(backoffMs -> {
        assertTrue(backoffMs >= startMs);
        assertTrue(backoffMs <= prevMs.get() * 3);
        assertTrue(backoffMs <= maxMs);
        prevMs.set(backoffMs);
    });
}

From source file:com.abhinavjhanwar.android.egg.neko.Cat.java

public static Cat create(Context context) {
    PrefState prefs = new PrefState(context);
    List<Cat> cats = prefs.getCats();
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        return new Cat(context, Math.abs(ThreadLocalRandom.current().nextInt()), cats);
    }/*from  w ww . ja  v  a2 s .  c  om*/
    return new Cat(context, Math.abs(new Random().nextInt()), cats);
}

From source file:org.apache.bookkeeper.common.conf.ConfigKeyTest.java

@Test
public void testGetDouble() {
    String keyName = runtime.getMethodName();
    double defaultValue = ThreadLocalRandom.current().nextDouble(10000.0f);
    ConfigKey key = ConfigKey.builder(keyName).required(true).type(Type.DOUBLE).defaultValue(defaultValue)
            .build();/*from  w  ww . ja  va2 s  . c  om*/

    Configuration conf = new ConcurrentConfiguration();

    // get default value
    assertEquals(defaultValue, key.getDouble(conf), 0.0001);
    assertEquals(defaultValue, key.get(conf));

    // set value
    double newValue = (defaultValue * 2);
    key.set(conf, newValue);
    assertEquals(newValue, key.getDouble(conf), 0.0001);
    assertEquals(newValue, key.get(conf));
}

From source file:io.hops.hopsworks.common.dao.tensorflow.config.TensorBoardProcessMgr.java

/**
 * Start the TensorBoard process//from   ww w  .  j a v a2  s  . co  m
 * @param project
 * @param user
 * @param hdfsUser
 * @param hdfsLogdir
 * @return
 * @throws IOException
 */
@TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED)
public TensorBoardDTO startTensorBoard(Project project, Users user, HdfsUsers hdfsUser, String hdfsLogdir)
        throws IOException {

    String prog = settings.getHopsworksDomainDir() + "/bin/tensorboard.sh";
    Process process = null;
    Integer port = 0;
    BigInteger pid = null;
    String tbBasePath = settings.getStagingDir() + Settings.TENSORBOARD_DIRS + File.separator;
    String projectUserUniquePath = project.getName() + "_" + hdfsUser.getName();
    String tbPath = tbBasePath + DigestUtils.sha256Hex(projectUserUniquePath);
    String certsPath = "\"\"";

    File tbDir = new File(tbPath);
    if (tbDir.exists()) {
        for (File file : tbDir.listFiles()) {
            if (file.getName().endsWith(".pid")) {
                String pidContents = com.google.common.io.Files.readFirstLine(file, Charset.defaultCharset());
                try {
                    pid = BigInteger.valueOf(Long.parseLong(pidContents));
                    if (pid != null && ping(pid) == 0) {
                        killTensorBoard(pid);
                    }
                } catch (NumberFormatException nfe) {
                    LOGGER.log(Level.WARNING,
                            "Expected number in pidfile " + file.getAbsolutePath() + " got " + pidContents);
                }
            }
        }
        FileUtils.deleteDirectory(tbDir);
    }
    tbDir.mkdirs();

    DistributedFileSystemOps dfso = dfsService.getDfsOps();
    try {
        certsPath = tbBasePath + DigestUtils.sha256Hex(projectUserUniquePath + "_certs");
        File certsDir = new File(certsPath);
        certsDir.mkdirs();
        HopsUtils.materializeCertificatesForUserCustomDir(project.getName(), user.getUsername(),
                settings.getHdfsTmpCertDir(), dfso, certificateMaterializer, settings, certsPath);
    } catch (IOException ioe) {
        LOGGER.log(Level.SEVERE,
                "Failed in materializing certificates for " + hdfsUser + " in directory " + certsPath, ioe);
        HopsUtils.cleanupCertificatesForUserCustomDir(user.getUsername(), project.getName(),
                settings.getHdfsTmpCertDir(), certificateMaterializer, certsPath, settings);
    } finally {
        if (dfso != null) {
            dfsService.closeDfsClient(dfso);
        }
    }

    String anacondaEnvironmentPath = settings.getAnacondaProjectDir(project.getName());
    int retries = 3;

    while (retries > 0) {

        if (retries == 0) {
            throw new IOException(
                    "Failed to start TensorBoard for project=" + project.getName() + ", user=" + user.getUid());
        }

        // use pidfile to kill any running servers
        port = ThreadLocalRandom.current().nextInt(40000, 59999);

        String[] command = new String[] { "/usr/bin/sudo", prog, "start", hdfsUser.getName(), hdfsLogdir,
                tbPath, port.toString(), anacondaEnvironmentPath, settings.getHadoopVersion(), certsPath,
                settings.getJavaHome() };

        LOGGER.log(Level.INFO, Arrays.toString(command));
        ProcessBuilder pb = new ProcessBuilder(command);

        try {
            // Send both stdout and stderr to the same stream
            pb.redirectErrorStream(true);

            process = pb.start();

            synchronized (pb) {
                try {
                    // Wait until the launcher bash script has finished
                    process.waitFor(20l, TimeUnit.SECONDS);
                } catch (InterruptedException ex) {
                    LOGGER.log(Level.SEVERE, "Woken while waiting for the TensorBoard to start: {0}",
                            ex.getMessage());
                }
            }

            int exitValue = process.exitValue();
            String pidPath = tbPath + File.separator + port + ".pid";
            File pidFile = new File(pidPath);
            // Read the pid for TensorBoard server
            if (pidFile.exists()) {
                String pidContents = com.google.common.io.Files.readFirstLine(pidFile,
                        Charset.defaultCharset());
                pid = BigInteger.valueOf(Long.parseLong(pidContents));
            }
            if (exitValue == 0 && pid != null) {
                int maxWait = 10;
                String logFilePath = tbPath + File.separator + port + ".log";
                File logFile = new File(logFilePath);
                while (maxWait > 0) {
                    String logFileContents = com.google.common.io.Files.readFirstLine(logFile,
                            Charset.defaultCharset());
                    // It is not possible to have a fixed wait time before showing the TB, we need to be sure it has started
                    if (logFile.length() > 0
                            && (logFileContents.contains("Loaded") | logFileContents.contains("Reloader")
                                    | logFileContents.contains("event")) | maxWait == 1) {
                        Thread.currentThread().sleep(5000);
                        TensorBoardDTO tensorBoardDTO = new TensorBoardDTO();
                        String host = null;
                        try {
                            host = InetAddress.getLocalHost().getHostAddress();
                        } catch (UnknownHostException ex) {
                            Logger.getLogger(TensorBoardProcessMgr.class.getName()).log(Level.SEVERE, null, ex);
                        }
                        tensorBoardDTO.setEndpoint(host + ":" + port);
                        tensorBoardDTO.setPid(pid);
                        return tensorBoardDTO;
                    } else {
                        Thread.currentThread().sleep(1000);
                        maxWait--;
                    }
                }
                TensorBoardDTO tensorBoardDTO = new TensorBoardDTO();
                tensorBoardDTO.setPid(pid);
                String host = null;
                try {
                    host = InetAddress.getLocalHost().getHostAddress();
                } catch (UnknownHostException ex) {
                    Logger.getLogger(TensorBoardProcessMgr.class.getName()).log(Level.SEVERE, null, ex);
                }
                tensorBoardDTO.setEndpoint(host + ":" + port);
                return tensorBoardDTO;
            } else {
                LOGGER.log(Level.SEVERE,
                        "Failed starting TensorBoard got exitcode " + exitValue + " retrying on new port");
                if (pid != null) {
                    this.killTensorBoard(pid);
                }
                pid = null;
            }

        } catch (Exception ex) {
            LOGGER.log(Level.SEVERE, "Problem starting TensorBoard: {0}", ex);
            if (process != null) {
                process.destroyForcibly();
            }
        } finally {
            retries--;
        }
    }

    //Failed to start TensorBoard, make sure there is no process running for it! (This should not be needed)
    if (pid != null && this.ping(pid) == 0) {
        this.killTensorBoard(pid);
    }

    //Certificates cleanup in case they were materialized but no TB started successfully

    dfso = dfsService.getDfsOps();
    certsPath = tbBasePath + DigestUtils.sha256Hex(projectUserUniquePath + "_certs");
    File certsDir = new File(certsPath);
    certsDir.mkdirs();
    try {
        HopsUtils.cleanupCertificatesForUserCustomDir(user.getUsername(), project.getName(),
                settings.getHdfsTmpCertDir(), certificateMaterializer, certsPath, settings);
    } finally {
        if (dfso != null) {
            dfsService.closeDfsClient(dfso);
        }
    }

    return null;
}

From source file:com.weibo.api.motan.filter.ServiceMockFilter.java

private long caclSleepTime(MockInfo info) {
    double rMean = info.totalSleepTime.doubleValue() / info.callNum.get();

    long sleepTime;

    int n = ThreadLocalRandom.current().nextInt(1000);

    long delta = (long) (rMean - info.mean + 1);
    if (n < 900) {
        sleepTime = info.p90;/*from  w  w w  .  j av a  2  s . c om*/
    } else if (900 <= n && n < 990) {
        sleepTime = info.p99;
    } else if (990 <= n && n < 999) {
        sleepTime = info.p999;
    } else {
        sleepTime = info.p999 + 1;
    }

    // Use 0ms to offset the mean time.
    sleepTime = delta > 0 ? 0 : sleepTime;

    info.totalSleepTime.addAndGet(sleepTime);

    // Throw runtimeException when errorRate is defined.
    if (info.errorRate != 0) {
        int rate = 1;
        while (info.errorRate * rate < 1) {
            rate *= 10;
        }
        if (ThreadLocalRandom.current().nextInt(rate) == 1) {
            throw new RuntimeException();
        }
    }

    return sleepTime;
}