List of usage examples for java.util.concurrent ThreadLocalRandom nextInt
public int nextInt(int bound)
From source file:fi.luontola.cqrshotel.JsonSerializationTest.java
private static <T> T pickRandom(Collection<T> values) { ThreadLocalRandom random = ThreadLocalRandom.current(); return values.stream().skip(random.nextInt(values.size())).findFirst().get(); }
From source file:fr.gouv.vitam.mdbes.QueryBench.java
private static String getRequest(JsonNode request, List<TypeField> fields, AtomicLong rank, BenchContext bench) {//from w ww .ja va 2s . co m if (fields != null && !fields.isEmpty()) { String finalRequest = request.toString(); ThreadLocalRandom rnd = ThreadLocalRandom.current(); for (TypeField field : fields) { String val = null; switch (field.type) { case save: finalRequest = getFinalRequest(field, "", bench.savedNames, finalRequest); break; case liste: int rlist = rnd.nextInt(field.listeValeurs.length); val = field.listeValeurs[rlist]; finalRequest = getFinalRequest(field, val, bench.savedNames, finalRequest); break; case listeorder: long i = rank.getAndIncrement(); if (i >= field.listeValeurs.length) { i = field.listeValeurs.length - 1; } val = field.listeValeurs[(int) i]; finalRequest = getFinalRequest(field, val, bench.savedNames, finalRequest); break; case serie: AtomicLong newcpt = rank; if (field.idcpt != null) { newcpt = bench.cpts.get(field.idcpt); if (newcpt == null) { newcpt = rank; System.err.println("wrong cpt name: " + field.idcpt); } } long j = newcpt.getAndIncrement(); if (field.modulo > 0) { j = j % field.modulo; } val = (field.prefix != null ? field.prefix : "") + j; finalRequest = getFinalRequest(field, val, bench.savedNames, finalRequest); break; case interval: int newval = rnd.nextInt(field.low, field.high + 1); finalRequest = getFinalRequest(field, "" + newval, bench.savedNames, finalRequest); break; default: break; } } return finalRequest; } return null; }
From source file:com.bitranger.parknshop.common.service.ads.ItemAdService.java
public List<PsPromotItem> randomReduce(List<PsPromotItem> src, int limit) { if (src.size() > limit) { ThreadLocalRandom rand = ThreadLocalRandom.current(); int idx = rand.nextInt(limit); int nidx = rand.nextInt(limit, src.size()); src.set(idx, src.get(nidx));/* w w w .j a va 2s. c o m*/ return new ArrayList<>(src.subList(0, limit)); } else { return src; } }
From source file:com.linkedin.pinot.integration.tests.UploadRefreshDeleteIntegrationTest.java
@Test(enabled = false) public void testUploadRefreshDelete() throws Exception { final int THREAD_COUNT = 1; final int SEGMENT_COUNT = 5; final int MIN_ROWS_PER_SEGMENT = 500; final int MAX_ROWS_PER_SEGMENT = 1000; final int OPERATIONS_PER_ITERATION = 10; final int ITERATION_COUNT = 5; final double UPLOAD_PROBABILITY = 0.8d; final String[] segmentNames = new String[SEGMENT_COUNT]; final int[] segmentRowCounts = new int[SEGMENT_COUNT]; for (int i = 0; i < SEGMENT_COUNT; i++) { segmentNames[i] = "segment_" + i; segmentRowCounts[i] = 0;/*from w w w. ja v a 2s . c om*/ } for (int i = 0; i < ITERATION_COUNT; i++) { // Create THREAD_COUNT threads ExecutorService executorService = Executors.newFixedThreadPool(THREAD_COUNT); // Submit OPERATIONS_PER_ITERATION uploads/deletes for (int j = 0; j < OPERATIONS_PER_ITERATION; j++) { executorService.submit(new Runnable() { @Override public void run() { try { ThreadLocalRandom random = ThreadLocalRandom.current(); // Pick a random segment int segmentIndex = random.nextInt(SEGMENT_COUNT); String segmentName = segmentNames[segmentIndex]; // Pick a random operation if (random.nextDouble() < UPLOAD_PROBABILITY) { // Upload this segment LOGGER.info("Will upload segment {}", segmentName); synchronized (segmentName) { // Create a segment with a random number of rows int segmentRowCount = random.nextInt(MIN_ROWS_PER_SEGMENT, MAX_ROWS_PER_SEGMENT); LOGGER.info("Generating and uploading segment {} with {} rows", segmentName, segmentRowCount); generateAndUploadRandomSegment(segmentName, segmentRowCount); // Store the number of rows LOGGER.info("Uploaded segment {} with {} rows", segmentName, segmentRowCount); segmentRowCounts[segmentIndex] = segmentRowCount; } } else { // Delete this segment LOGGER.info("Will delete segment {}", segmentName); synchronized (segmentName) { // Delete this segment LOGGER.info("Deleting segment {}", segmentName); String reply = sendDeleteRequest( ControllerRequestURLBuilder.baseUrl(CONTROLLER_BASE_API_URL) .forSegmentDelete("myresource", segmentName)); LOGGER.info("Deletion returned {}", reply); // Set the number of rows to zero LOGGER.info("Deleted segment {}", segmentName); segmentRowCounts[segmentIndex] = 0; } } } catch (Exception e) { throw new RuntimeException(e); } } }); } // Await for all tasks to complete executorService.shutdown(); executorService.awaitTermination(5L, TimeUnit.MINUTES); // Count number of expected rows int expectedRowCount = 0; for (int segmentRowCount : segmentRowCounts) { expectedRowCount += segmentRowCount; } // Wait for up to one minute for the row count to match the expected row count LOGGER.info("Awaiting for the row count to match {}", expectedRowCount); int pinotRowCount = (int) getCurrentServingNumDocs(); long timeInOneMinute = System.currentTimeMillis() + 60 * 1000L; while (System.currentTimeMillis() < timeInOneMinute && pinotRowCount != expectedRowCount) { LOGGER.info("Row count is {}, expected {}, awaiting for row count to match", pinotRowCount, expectedRowCount); Thread.sleep(5000L); try { pinotRowCount = (int) getCurrentServingNumDocs(); } catch (Exception e) { LOGGER.warn("Caught exception while sending query to Pinot, retrying", e); } } // Compare row counts Assert.assertEquals(pinotRowCount, expectedRowCount, "Expected and actual row counts don't match after waiting one minute"); } }
From source file:com.pushtechnology.consulting.SessionCreator.java
/** * Create a finite number of sessions.//ww w. j av a 2 s. c om */ private void doStart(int maxNumberSessions) { LOG.trace("SessionCreator#doStart for '{}' sessions ", maxNumberSessions); long delay = 0L; final CountDownLatch sessionsLatch = new CountDownLatch(maxNumberSessions); final CountDownLatch subscriptionLatch = new CountDownLatch(maxNumberSessions * topicSelectors.size()); for (int i = 0; i < maxNumberSessions; i++) { addSessions.add(Benchmarker.globalThreadPool.schedule(new Runnable() { @Override public void run() { LOG.trace("Adding session"); try { /* ASYNC session creation */ sessionFactory.open(getConnectionString(), new OpenCallback(sessionsLatch, subscriptionLatch)); LOG.trace("Done submitting session open"); } catch (Exception e) { /* ASYNC session creation */ connectionFailures.incrementAndGet(); sessionsLatch.countDown(); LOG.error("Exception caught trying to connect", e); } } private String getConnectionString() { final ThreadLocalRandom rnd = ThreadLocalRandom.current(); return connectionStrings.get(rnd.nextInt(connectionStrings.size())); } }, ++delay % 500, MILLISECONDS)); } try { final int remainingWait = 15 * 60; // Ensure all sessions connected sessionsLatch.await(remainingWait, SECONDS); // Countdown the subscriptions subscriptionLatch.await(remainingWait, SECONDS); } catch (InterruptedException e) { LOG.error("Exception caught waiting for sessions to open: '{}'", e); } // all connected/failed but not processed all the subscriptions yet. writeSteadyStateFlagFile(); LOG.trace("Done SessionCreator#doStart"); }
From source file:com.pushtechnology.consulting.SessionCreator.java
/** * Session churn.//from w w w.j ava2 s . com * * @param multiIpClientAddresses * @param sessionCreateRatePerSec * @param sessionDurationMs */ private void doStart(long sessionCreateRatePerSec, long sessionDurationSec) { LOG.trace("SessionCreator#doStart for '{}' sessions/second and '{}' sessionDurationMs", sessionCreateRatePerSec, sessionDurationSec); final long interval = 1000 / sessionCreateRatePerSec; long now = System.currentTimeMillis(); do { try { startedSessions.incrementAndGet(); Benchmarker.connectThreadPool.submit(new Runnable() { @Override public void run() { LOG.trace("Adding session"); try { /* ASYNC session creation */ sessionFactory.open(getConnectionString(), new OpenChurningSessionCallback(sessionDurationSec)); LOG.trace("Done submitting session open"); } catch (Exception e) { /* ASYNC session creation */ connectionFailures.incrementAndGet(); LOG.error("Exception caught trying to connect:", e); } } private String getConnectionString() { final ThreadLocalRandom rnd = ThreadLocalRandom.current(); return connectionStrings.get(rnd.nextInt(connectionStrings.size())); } }); } catch (Exception e) { LOG.error("Exception caught when submitting session open ", e.getMessage()); connectionFailures.incrementAndGet(); } if (connectedSessions.get() >= sessionCreateRatePerSec * sessionDurationSec) { writeSteadyStateFlagFile(); } now = now + interval; LockSupport.parkUntil(now); } while (true); }
From source file:LinkedTransferQueue.java
/** * Spins/yields/blocks until node s is matched or caller gives up. * * @param s the waiting node/*w w w . j av a 2s . co m*/ * @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 E awaitMatch(Node s, Node pred, E e, boolean timed, long nanos) { long lastTime = timed ? System.nanoTime() : 0L; Thread w = Thread.currentThread(); int spins = -1; // initialized after first item and cancel checks ThreadLocalRandom randomYields = null; // bound if needed for (;;) { Object item = s.item; if (item != e) { // matched assert item != s; s.forgetContents(); // avoid garbage return this.<E>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) Thread.yield(); // occasionally yield } else if (s.waiter == null) { s.waiter = w; // request unpark then recheck } else if (timed) { long now = System.nanoTime(); if ((nanos -= now - lastTime) > 0) LockSupport.parkNanos(this, nanos); lastTime = now; } else { LockSupport.park(this); } } }
From source file:zz.pseas.ghost.utils.LoginUtils.java
public static void sleep(long millis) { //Random rand = new Random(System.currentTimeMillis()); ThreadLocalRandom tlr = ThreadLocalRandom.current(); // ??30///* w w w . j a v a 2 s .com*/ int minInternalTime = 1 * 1000; int maxInternalTime = (int) millis; int randnum = 0; if (maxInternalTime < minInternalTime) { maxInternalTime = 3 * minInternalTime + 1; } randnum = tlr.nextInt(maxInternalTime) % (maxInternalTime - minInternalTime + 1) + minInternalTime; // if (randnum <= 0) return; try { Thread.sleep(randnum); //Thread.currentThread().sleep(randnum); } catch (InterruptedException e) { } }