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.hops.hopsworks.common.dao.rstudio.RStudioSettingsFacade.java

public RStudioSettings findByProjectUser(int projectId, String email) {

    RStudioSettingsPK pk = new RStudioSettingsPK(projectId, email);
    RStudioSettings js = null;/*from  ww w  .  j a va2s .com*/
    js = em.find(RStudioSettings.class, pk);
    if (js == null) {
        String secret = DigestUtils.sha256Hex(Integer.toString(ThreadLocalRandom.current().nextInt()));
        js = new RStudioSettings(pk);
        js.setSecret(secret);
        js.setMode("sparkDynamic");
        persist(js);
    }
    return js;

}

From source file:org.apache.hadoop.hdfs.TestLeaseRecoveryStriped.java

private static int[][][] getBlockLengthsSuite() {
    final int groups = 4;
    final int minNumCell = 3;
    final int maxNumCell = 11;
    final int minNumDelta = -4;
    final int maxNumDelta = 2;
    int delta = 0;
    int[][][] blkLenSuite = new int[groups][][];
    Random random = ThreadLocalRandom.current();
    for (int i = 0; i < blkLenSuite.length; i++) {
        if (i == blkLenSuite.length - 1) {
            delta = bytesPerChecksum;/*from   ww  w  . ja  v a2  s  .  c o m*/
        }
        int[][] suite = new int[2][];
        int[] lens = new int[NUM_DATA_BLOCKS + NUM_PARITY_BLOCKS];
        long[] lenInLong = new long[lens.length];
        for (int j = 0; j < lens.length; j++) {
            int numCell = random.nextInt(maxNumCell - minNumCell + 1) + minNumCell;
            int numDelta = j < NUM_DATA_BLOCKS ? random.nextInt(maxNumDelta - minNumDelta + 1) + minNumDelta
                    : 0;
            lens[j] = CELL_SIZE * numCell + delta * numDelta;
            lenInLong[j] = lens[j];
        }
        suite[0] = lens;
        suite[1] = new int[] { (int) StripedBlockUtil.getSafeLength(ecPolicy, lenInLong) };
        blkLenSuite[i] = suite;
    }
    return blkLenSuite;
}

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

private Set<String> getRandomWords() {
    Set<String> results = new HashSet<>();

    int n = ThreadLocalRandom.current().nextInt(1, 8);
    for (int i = 0; i < n; i++) {
        int index = ThreadLocalRandom.current().nextInt(0, NEIGHBORS.size());
        results.add(NEIGHBORS.get(index));
    }//from   ww  w. ja  va  2 s  .  co  m

    return results;
}

From source file:com.facebook.presto.operator.aggregation.BootstrappedAggregation.java

@Override
public Accumulator createIntermediateAggregation(double confidence) {
    return createDeterministicIntermediateAggregation(confidence, ThreadLocalRandom.current().nextLong());
}

From source file:org.apache.druid.indexing.common.task.RealtimeIndexTask.java

public static String makeRandomId() {
    final StringBuilder suffix = new StringBuilder(TASK_ID_LENGTH);
    int randomBits = ThreadLocalRandom.current().nextInt();
    for (int i = 0; i < TASK_ID_LENGTH; i++) {
        suffix.append((char) ('a' + ((randomBits >>> (i * TASK_ID_BITS_PER_SYMBOL)) & TASK_ID_SYMBOL_MASK)));
    }/*w w  w.j  a v a2 s  .  c  om*/
    return suffix.toString();
}

From source file:org.verdictdb.sqlwriter.CreateTableToSql.java

private String createImpalaPartitionTableToSql(CreateScrambledTableQuery query) throws VerdictDBException {

    // 1. This method should only get called when the target DB is Impala.
    // 2. Currently, Impala's create-table-as-select has a bug; dynamic partitioning is faulty
    // when used in conjunction with rand();
    if (!(syntax instanceof ImpalaSyntax)) {
        throw new VerdictDBException("Target database must be Impala.");
    }//from  w  w  w . j  a va 2  s.c o  m

    StringBuilder sql = new StringBuilder();

    String schemaName = query.getSchemaName();
    String tableName = query.getTableName();
    SelectQuery select = query.getSelect();

    // this table will be created and dropped at the end
    int randomNum = ThreadLocalRandom.current().nextInt(0, 10000);
    String tempTableName = "verdictdb_scrambling_temp_" + randomNum;

    // create a non-partitioned temp table as a select
    CreateTableAsSelectQuery tempCreate = new CreateTableAsSelectQuery(schemaName, tempTableName, select);
    sql.append(QueryToSql.convert(syntax, tempCreate));
    sql.append(";");

    // insert the temp table into a partitioned table.
    String aliasName = "t";
    SelectQuery selectAllFromTemp = SelectQuery.create(new AsteriskColumn(),
            new BaseTable(schemaName, tempTableName, aliasName));
    CreateTableAsSelectQuery insert = new CreateTableAsSelectQuery(schemaName, tableName, selectAllFromTemp);
    for (String col : query.getPartitionColumns()) {
        insert.addPartitionColumn(col);
    }
    sql.append(QueryToSql.convert(syntax, insert));
    sql.append(";");

    // drop the temp table
    DropTableQuery drop = new DropTableQuery(schemaName, tempTableName);
    sql.append(QueryToSql.convert(syntax, drop));
    sql.append(";");

    return sql.toString();
}

From source file:com.nesscomputing.quartz.QuartzJob.java

/**
 * Set the time-of-day when the first run of the job will take place.
 *//*from   ww  w  .  j a  va 2 s .  c o  m*/
@SuppressWarnings("unchecked")
public final SelfType startTime(final DateTime when, final TimeSpan jitter) {
    // Find the current week day in the same time zone as the "when" time passed in.
    final DateTime now = new DateTime().withZone(when.getZone());

    final int startWeekDay = when.getDayOfWeek();
    final int currentWeekDay = now.getDayOfWeek();

    // ( x + n ) % n is x for x > 0 and n - x for x < 0.
    final int daysTilStart = (startWeekDay - currentWeekDay + DAYS_PER_WEEK) % DAYS_PER_WEEK;
    Preconditions.checkState(daysTilStart >= 0 && daysTilStart < DAYS_PER_WEEK,
            "daysTilStart must be 0..%s, but is %s", DAYS_PER_WEEK, daysTilStart);

    // same trick as above, add a full week in millis and do the modulo.
    final long millisecondsTilStart = (when.getMillisOfDay() - now.getMillisOfDay()
            + daysTilStart * MILLIS_PER_DAY + MILLIS_PER_WEEK) % MILLIS_PER_WEEK;
    Preconditions.checkState(millisecondsTilStart >= 0 && millisecondsTilStart < MILLIS_PER_WEEK,
            "millisecondsTilStart must be 0..%s, but is %s", MILLIS_PER_WEEK, millisecondsTilStart);

    this.delay = Duration.millis(
            (long) (ThreadLocalRandom.current().nextDouble() * jitter.getMillis()) + millisecondsTilStart);
    return (SelfType) this;
}

From source file:org.workspace7.moviestore.utils.MovieDBHelper.java

/**
 * This method queries the external API and caches the movies, for the demo purpose we just query only first page
 *
 * @return - the status code of the invocation
 *///  w  ww  .  j a va2  s.  c  o  m
protected int queryAndCache() {

    if (this.moviesCache.isEmpty()) {

        log.info("No movies exist in cache, loading cache ..");

        UriComponentsBuilder moviesUri = UriComponentsBuilder
                .fromUriString(movieStoreProps.getApiEndpointUrl() + "/movie/popular")
                .queryParam("api_key", movieStoreProps.getApiKey());

        final URI requestUri = moviesUri.build().toUri();

        log.info("Request URI:{}", requestUri);

        ResponseEntity<String> response = restTemplate.getForEntity(requestUri, String.class);

        log.info("Response Status:{}", response.getStatusCode());

        Map<String, Movie> movieMap = new HashMap<>();

        if (200 == response.getStatusCode().value()) {
            String jsonBody = response.getBody();
            ObjectMapper objectMapper = new ObjectMapper();
            try {
                JsonNode root = objectMapper.readTree(jsonBody);
                JsonNode results = root.path("results");
                results.elements().forEachRemaining(movieNode -> {
                    String id = movieNode.get("id").asText();
                    Movie movie = Movie.builder().id(id).overview(movieNode.get("overview").asText())
                            .popularity(movieNode.get("popularity").floatValue())
                            .posterPath("http://image.tmdb.org/t/p/w92" + movieNode.get("poster_path").asText())
                            .logoPath("http://image.tmdb.org/t/p/w45" + movieNode.get("poster_path").asText())
                            .title(movieNode.get("title").asText())
                            .price(ThreadLocalRandom.current().nextDouble(1.0, 10.0)).build();
                    movieMap.put(id, movie);
                });
            } catch (IOException e) {
                log.error("Error reading response:", e);
            }

            log.debug("Got {} movies", movieMap);
            moviesCache.putAll(movieMap);
        }
        return response.getStatusCode().value();
    } else {
        log.info("Cache already loaded with movies ... will use cache");
        return 200;
    }
}

From source file:com.facebook.presto.operator.aggregation.AbstractTestApproximateCountDistinct.java

@Test(dataProvider = "provideStandardErrors")
public void testMultiplePositionsPartial(double maxStandardError) throws Exception {
    for (int i = 0; i < 100; ++i) {
        int uniques = ThreadLocalRandom.current().nextInt(20000) + 1;
        List<Object> values = createRandomSample(uniques, (int) (uniques * 1.5));
        assertEquals(estimateCountPartial(values, maxStandardError),
                estimateGroupByCount(values, maxStandardError));
    }//from  w  w w. jav a  2 s  .  co  m
}

From source file:org.apache.phoenix.loadbalancer.service.LoadBalancer.java

/**
 * It returns the location of Phoenix Query Server
 * in form of Guava <a href="https://google.github.io/guava/releases/19.0/api/docs/com/google/common/net/HostAndPort.html">HostAndPort</a>
 * from the cache. The client should catch Exception incase
 * the method is unable to fetch PQS location due to network failure or
 * in-correct configuration issues./*www. jav  a  2  s.  c o m*/
 * @return - return Guava HostAndPort. See <a href="http://google.com">http://google.com</a>
 * @throws Exception
 */
public HostAndPort getSingleServiceLocation() throws Exception {
    List<HostAndPort> childNodes = conductSanityCheckAndReturn();
    // get an random connect string
    int i = ThreadLocalRandom.current().nextInt(0, childNodes.size());
    return childNodes.get(i);
}