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:com.linkedin.pinot.integration.tests.UploadRefreshDeleteIntegrationTest.java

protected void generateAndUploadRandomSegment(String segmentName, int rowCount) throws Exception {
    ThreadLocalRandom random = ThreadLocalRandom.current();
    Schema schema = new Schema.Parser().parse(
            new File(TestUtils.getFileFromResourceUrl(getClass().getClassLoader().getResource("dummy.avsc"))));
    GenericRecord record = new GenericData.Record(schema);
    GenericDatumWriter<GenericRecord> datumWriter = new GenericDatumWriter<GenericRecord>(schema);
    DataFileWriter<GenericRecord> fileWriter = new DataFileWriter<GenericRecord>(datumWriter);
    File avroFile = new File(_tmpDir, segmentName + ".avro");
    fileWriter.create(schema, avroFile);

    for (int i = 0; i < rowCount; i++) {
        record.put(0, random.nextInt());
        fileWriter.append(record);/* ww  w .ja va2s. c o  m*/
    }

    fileWriter.close();

    int segmentIndex = Integer.parseInt(segmentName.split("_")[1]);

    File segmentTarDir = new File(_tarsDir, segmentName);
    ensureDirectoryExistsAndIsEmpty(segmentTarDir);
    ExecutorService executor = MoreExecutors.sameThreadExecutor();
    buildSegmentsFromAvro(Collections.singletonList(avroFile), executor, segmentIndex,
            new File(_segmentsDir, segmentName), segmentTarDir, "mytable", false, null);
    executor.shutdown();
    executor.awaitTermination(1L, TimeUnit.MINUTES);

    for (String segmentFileName : segmentTarDir.list()) {
        File file = new File(segmentTarDir, segmentFileName);
        FileUploadUtils.sendFile("localhost", "8998", "segments", segmentFileName, new FileInputStream(file),
                file.length(), FileUploadUtils.SendFileMethod.POST);
    }

    avroFile.delete();
    FileUtils.deleteQuietly(segmentTarDir);
}

From source file:org.apache.usergrid.persistence.actorsystem.ClientActor.java

@Override
public void onReceive(Object message) {

    int startSize = nodes.size();

    String routerPath = routersByMessageType.get(message.getClass());

    if (routerPath != null && ready) {

        // just pick any node, the ClusterSingletonRouter will do the consistent hash routing
        List<Address> nodesList = new ArrayList<>(nodes);
        Address address = nodesList.get(ThreadLocalRandom.current().nextInt(nodesList.size()));
        ActorSelection service = getContext().actorSelection(address + routerPath);
        service.tell(message, getSender());

    } else if (routerPath != null && !ready) {

        logger.debug("{} responding with status unknown", name);
        getSender().tell(new ErrorResponse("ClientActor not ready"), getSender());

    } else if (message instanceof StatusRequest) {
        if (ready) {
            getSender().tell(new StatusMessage(name, StatusMessage.Status.READY), getSender());
        } else {//from w ww  .  j a v  a 2s  .  c  om
            getSender().tell(new StatusMessage(name, StatusMessage.Status.INITIALIZING), getSender());
        }
        return;

    } else {
        processAsClusterEvent(message);
    }

    if (logger.isDebugEnabled() && startSize != nodes.size()) {
        logger.debug("{} now knows {} nodes", name, nodes.size());
    }

    if (!nodes.isEmpty() && !ready) {
        logger.debug(name + " is ready");
        ready = true;

    } else if (nodes.isEmpty() && ready) {
        ready = false;
    }
}

From source file:cgg.informatique.jfl.labo10.modeles.Token.java

/**
 * Generate a random salt that comply with the folowing policy 
 * <p>The policy for a token's salt is:</p>
 * <ul>/*from www.j a  v  a 2  s .  c  o  m*/
 *  <li><p>At least 8 chars</p></li>
 *  <li><p>No longer than 50 chars</p></li>
 *   </ul>
 * @return salt
 */
private static String generateRdmSalt() {
    int length = ThreadLocalRandom.current().nextInt(8, 50 + 1);
    return RandomStringUtils.randomAlphabetic(length);
}

From source file:com.toptal.conf.SampleDataConfiguration.java

/**
 * Adds entries to the given user.//from  www . java  2 s  .  c o  m
 * @param user User.
 */
@SuppressWarnings("PMD.AvoidInstantiatingObjectsInLoops")
private void addEntries(final User user) {
    final ThreadLocalRandom rnd = ThreadLocalRandom.current();
    final int size = rnd.nextInt(10, 100);
    final Calendar cal = Calendar.getInstance();
    final long end = cal.getTimeInMillis();
    cal.set(Calendar.MONTH, cal.get(Calendar.MONTH) - 2);
    final long start = cal.getTimeInMillis();
    for (int idx = 0; idx < size; ++idx) {
        this.entries.save(Entry.builder().date(new Date(rnd.nextLong(start, end)))
                // @checkstyle MagicNumberCheck (2 lines)
                .distance(rnd.nextLong(500, 10000)).time(rnd.nextLong(120000, 2400000)).user(user).build());
    }
}

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

@Test(dataProvider = "provideStandardErrors")
public void testMixedNullsAndNonNulls(double maxStandardError) throws Exception {
    List<Object> baseline = createRandomSample(10000, 15000);

    // 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());
    }/*from  ww  w . j  ava  2s  .c  o  m*/

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

From source file:reactivity.SseController.java

/**
 * Generates a random artifact.//  w w w.  jav  a2  s  . c  o m
 *
 * @return the timestamp associated to that artifact
 */
@PostMapping("/sse/artifacts")
long artifact() {
    final Map<String, Object> categories = new HashMap<>();
    final BiConsumer<String, String[]> populator = (key, values) -> {
        final String value = values[ThreadLocalRandom.current().nextInt(0, values.length)];

        if (value != null) {
            categories.put(key, value);
        }
    };

    populator.accept("assignee", new String[] { "ndamie", "gdrouet", "asanchez", "qlevaslot", "cazelart",
            "fclety", "hazarian", null });
    populator.accept("category", new String[] { "bug", "feature", "question", null });
    populator.accept("description",
            new String[] { "foo bar baz", "some description", "reactivity is awesome", null });
    populator.accept("color", new String[] { "blue", "green", "red", "yellow", null });
    populator.accept("priority", new String[] { "high", "low", "medium", null });

    final Group group;

    if (Math.random() < 0.5) {
        group = new Group("personal", "gdrouet");
    } else {
        group = new Group("organization", "org" + (char) ThreadLocalRandom.current().nextInt(65, 70));
    }

    final Artifact a = new Artifact("default", group, categories);
    final Observable<JsonDocument> o = repository.add(a);
    o.subscribe(d -> replayProcessor.onNext(sse(a)));
    o.subscribe(d -> timeseries(a));

    return a.getTimestamp();
}

From source file:org.talend.components.salesforce.integration.SalesforceTestBase.java

public static String createNewRandom() {
    return Integer.toString(ThreadLocalRandom.current().nextInt(1, 1000000));
}

From source file:com.navercorp.pinpoint.web.vo.stat.chart.ResponseTimeChartGroupTest.java

private SampledResponseTime createSampledResponseTime(long timestamp, int maxConnectionSize) {
    int listSize = RandomUtils.nextInt(1, RANDOM_LIST_MAX_SIZE);

    List<ResponseTimeBo> responseTimeBoList = new ArrayList<>(listSize);
    for (int i = 0; i < listSize; i++) {
        ResponseTimeBo responseTimeBo = new ResponseTimeBo();
        responseTimeBo.setAvg(ThreadLocalRandom.current().nextLong(RANDOM_AVG_MAX_SIZE));
        responseTimeBoList.add(responseTimeBo);
    }//from  w  w w .  j  a va 2 s.c om

    return sampler.sampleDataPoints(0, timestamp, responseTimeBoList, null);
}

From source file:sonicScream.utilities.StringParsing.java

private static void initSpecialCaseNames() {
    if (_specialCaseNames.isEmpty()) {
        //----HEROES-----
        String[] odFirstNames = new String[] { "outhouse", "offworld", "overgrown", "obsidian" };
        String[] odLastNames = new String[] { "demolisher", "destroyer", "desolator", "demonstrator" };

        _specialCaseNames.put("antimage", "anti_mage");
        _specialCaseNames.put("batrider", "bat_rider");
        _specialCaseNames.put("crystalmaiden", "crystal_maiden");
        _specialCaseNames.put("doombringer", "doom");
        _specialCaseNames.put("drowranger", "drow_ranger");
        _specialCaseNames.put("furion", "nature's_prophet");
        _specialCaseNames.put("lifestealer", "life_stealer");
        _specialCaseNames.put("nevermore", "shadow_fiend");
        _specialCaseNames.put("nightstalker", "night_stalker");

        //Heh, couldn't resist.
        if (ThreadLocalRandom.current().nextInt() % 100 == 0) {
            String firstName = odFirstNames[ThreadLocalRandom.current().nextInt(0, odFirstNames.length)];
            String lastName = odLastNames[ThreadLocalRandom.current().nextInt(0, odLastNames.length)];
            _specialCaseNames.put("obsidian_destroyer", firstName + "_ " + lastName);
        } else {//from  w w  w  . j  a v  a  2 s.co m
            _specialCaseNames.put("obsidian_destroyer", "outworld_devourer");
        }
        _specialCaseNames.put("queenofpain", "queen_of_pain");
        _specialCaseNames.put("rattletrap", "clockwerk");
        _specialCaseNames.put("shadowshaman", "shadown_shaman");
        _specialCaseNames.put("shredder", "timbersaw");
        _specialCaseNames.put("skeletonking", "wraith_king");
        _specialCaseNames.put("stormspirit", "storm_spirit");
        _specialCaseNames.put("treant", "treant_protector");
        _specialCaseNames.put("vengefulspirit", "vengeful_spirit");
        _specialCaseNames.put("windrunner", "windranger");
        _specialCaseNames.put("wisp", "io");
        _specialCaseNames.put("witchdoctor", "witch_doctor");
        _specialCaseNames.put("zuus", "zeus");

        //----ITEMS----

        //----ANNOUNCERS----

        //----MUSIC
    }
}

From source file:com.navercorp.pinpoint.web.vo.stat.chart.agent.ResponseTimeChartGroupTest.java

private SampledResponseTime createSampledResponseTime(long timestamp, int maxConnectionSize) {
    int listSize = RandomUtils.nextInt(1, RANDOM_LIST_MAX_SIZE);

    List<ResponseTimeBo> responseTimeBoList = new ArrayList<>(listSize);
    for (int i = 0; i < listSize; i++) {
        ResponseTimeBo responseTimeBo = new ResponseTimeBo();
        long avg = ThreadLocalRandom.current().nextLong(RANDOM_AVG_MAX_SIZE);
        responseTimeBo.setAvg(avg);//from   w w w . j a va  2  s  .  co m
        responseTimeBo.setMax(avg + 100);
        responseTimeBoList.add(responseTimeBo);
    }

    return sampler.sampleDataPoints(0, timestamp, responseTimeBoList, null);
}