@Test public void testRandomRangeAndBatches() throws ExecutionException, InterruptedException { ThreadLocalRandom random = ThreadLocalRandom.current(); int treeSize = random.nextInt(maxTreeSize / 10, maxTreeSize * 10); for (int i = 0; i < perThreadTrees / 10; i++) testInsertions(threads * 10, treeSize, random.nextInt(1, 100) / 10f, treeSize / 100, true); }
private static IntFunction<Integer> twoDiceThrows() { return i -> { final ThreadLocalRandom random = ThreadLocalRandom.current(); final int firstThrow = random.nextInt(1, 7); final int secondThrow = random.nextInt(1, 7); return firstThrow + secondThrow; }; }
/** @throws Exception If failed. */ public void testConcurrentStart() throws Exception { ThreadLocalRandom rnd = ThreadLocalRandom.current(); for (int i = 0; i < 3; i++) { try { clientNodes = new HashSet<>(); while (clientNodes.size() < 2) clientNodes.add(rnd.nextInt(1, NODES_CNT)); clientNodes.add(NODES_CNT - 1); log.info("Test iteration [iter=" + i + ", clients=" + clientNodes + ']'); Ignite srv = startGrid(0); // Start server node first. assertFalse(srv.configuration().isClientMode()); startGridsMultiThreaded(1, NODES_CNT - 1); checkTopology(NODES_CNT); awaitPartitionMapExchange(); for (int node : clientNodes) { Ignite ignite = grid(node); assertTrue(ignite.configuration().isClientMode()); } } finally { stopAllGrids(); } } }
@Override public MutatedInstanceMetaData<MultiMaskEfsmSkeleton, MultiMaskEfsmMutation> apply( MultiMaskEfsmSkeleton individual) { List<Step> transitions = getTransitions(individual); if (transitions.isEmpty()) { return new MutatedInstanceMetaData<MultiMaskEfsmSkeleton, MultiMaskEfsmMutation>( new MultiMaskEfsmSkeleton(individual), new MutationCollection<MultiMaskEfsmMutation>()); } MyMap num = new MyMap(); for (Step s : transitions) { num.put(s, 1); } for (VarsActionsScenario s : individual.getCounterExamples()) { getTrace(individual, s, num); } double sum = 0; for (Step s : transitions) { sum += num.get(s); } int i = 0; double cur = num.get(transitions.get(0)) / sum; ThreadLocalRandom random = ThreadLocalRandom.current(); while (random.nextDouble() > cur) { i++; cur += num.get(transitions.get(i)) / sum; } Step s = transitions.get(i); MultiMaskEfsmSkeleton ind = new MultiMaskEfsmSkeleton(individual); int x = random.nextInt(MultiMaskEfsmSkeleton.STATE_COUNT); ind.getState(s.state).getTransitionGroup(s.event, s.group).setNewState(s.index, x); return new MutatedInstanceMetaData<MultiMaskEfsmSkeleton, MultiMaskEfsmMutation>( ind, new MutationCollection<MultiMaskEfsmMutation>( new DestinationStateMutation(s.state, s.event, s.group, s.index, x))); }
public static ByteBuffer randomBytes(int quantity, ThreadLocalRandom tlr) { ByteBuffer slice = ByteBuffer.allocate(quantity); ByteBuffer source = dataSource.duplicate(); source.position(tlr.nextInt(source.capacity() - quantity)); source.limit(source.position() + quantity); slice.put(source); slice.flip(); return slice; }
private static RandomTree randomTreeByBuilder(int minSize, int maxSize) { assert minSize > 3; ThreadLocalRandom random = ThreadLocalRandom.current(); BTree.Builder<Integer> builder = BTree.builder(naturalOrder()); int targetSize = random.nextInt(minSize, maxSize); int maxModificationSize = (int) Math.sqrt(targetSize); TreeSet<Integer> canonical = new TreeSet<>(); int curSize = 0; TreeSet<Integer> ordered = new TreeSet<>(); List<Integer> shuffled = new ArrayList<>(); while (curSize < targetSize) { int nextSize = maxModificationSize <= 1 ? 1 : random.nextInt(1, maxModificationSize); // leave a random selection of previous values (random.nextBoolean() ? ordered.headSet(random.nextInt()) : ordered.tailSet(random.nextInt())) .clear(); shuffled = new ArrayList<>( shuffled.subList(0, shuffled.size() < 2 ? 0 : random.nextInt(shuffled.size() / 2))); for (int i = 0; i < nextSize; i++) { Integer next = random.nextInt(); ordered.add(next); shuffled.add(next); canonical.add(next); } switch (random.nextInt(5)) { case 0: builder.addAll(ordered); break; case 1: builder.addAll(BTreeSet.of(ordered)); break; case 2: for (Integer i : ordered) builder.add(i); case 3: builder.addAll(shuffled); break; case 4: for (Integer i : shuffled) builder.add(i); } curSize += nextSize; maxModificationSize = Math.min(maxModificationSize, targetSize - curSize); } BTreeSet<Integer> btree = BTreeSet.<Integer>wrap(builder.build(), naturalOrder()); Assert.assertEquals(canonical.size(), btree.size()); return new RandomTree(canonical, btree); }
/** * Erzeugt eine Datei mit der angegebenen Anzahl in sortierter Reihenfolge. Die Zahlen werden * hintereinander weg geschrieben und durch ein Leerzeichen getrennt. Die Range der zufaellig * generierten Zahlen ist 1..(quantity * 5) * * @param filename, Dateiname (Endung *.dat wird automatisch ergaenzt) * @param quantity, die Anzahl der zufaellig generierten Zahlen * @param desc, true = absteigend sortiert; false = aufsteigend sortiert */ public static void sortNum(String filename, int quantity, boolean desc) { File file = new File(filename + ".dat"); if (file.exists()) { System.err.println("Die Datei existiert bereits"); } else { try { file.createNewFile(); } catch (IOException e) { e.printStackTrace(); } BufferedWriter bw = null; try { FileWriter fw = new FileWriter(file); bw = new BufferedWriter(fw); ThreadLocalRandom random = ThreadLocalRandom.current(); List<Integer> list = new ArrayList<Integer>(); for (int i = 1; i <= quantity; i++) { list.add(random.nextInt(1, quantity * 5)); } Collections.sort(list); if (desc) { Collections.reverse(list); for (int i = 1; i < list.size(); i++) { bw.write(String.valueOf(list.get(i)) + " "); } bw.write(String.valueOf(list.get(list.size() - 1))); } else { for (int i = 1; i < list.size(); i++) { bw.write(String.valueOf(list.get(i)) + " "); } bw.write(String.valueOf(list.get(list.size() - 1))); } System.err.println("Die Datei " + filename + ".dat wurde erfolgreich erstellt"); } catch (IOException e) { e.printStackTrace(); } finally { try { bw.close(); } catch (IOException e) { e.printStackTrace(); } } } }
private static RandomTree randomTreeByUpdate(int minSize, int maxSize) { assert minSize > 3; TreeSet<Integer> canonical = new TreeSet<>(); ThreadLocalRandom random = ThreadLocalRandom.current(); int targetSize = random.nextInt(minSize, maxSize); int maxModificationSize = random.nextInt(2, targetSize); Object[] accmumulate = BTree.empty(); int curSize = 0; while (curSize < targetSize) { int nextSize = maxModificationSize == 1 ? 1 : random.nextInt(1, maxModificationSize); TreeSet<Integer> build = new TreeSet<>(); for (int i = 0; i < nextSize; i++) { Integer next = random.nextInt(); build.add(next); canonical.add(next); } accmumulate = BTree.update(accmumulate, naturalOrder(), build, UpdateFunction.<Integer>noOp()); curSize += nextSize; maxModificationSize = Math.min(maxModificationSize, targetSize - curSize); } return new RandomTree(canonical, BTreeSet.<Integer>wrap(accmumulate, naturalOrder())); }
/** * Erzeugt eine Datei mit der angegebenen Anzahl an zufaelligen Zahlen. Die Zahlen werden * hintereinander weg geschrieben und durch ein Leerzeichen getrennt. Die Range der zufaelligen * Zahlen ist 1..(quantity * 5) * * @param filename, Dateiname (Endung *.dat wird automatisch ergaenzt) * @param quantity, die Anzahl der zufaellig generierten Zahlen */ public static void sortNum(String filename, int quantity) { File file = new File(filename + ".dat"); if (file.exists()) { System.err.println("Die Datei existiert bereits"); } else { try { file.createNewFile(); } catch (IOException e) { e.printStackTrace(); } BufferedWriter bw = null; try { FileWriter fw = new FileWriter(file); bw = new BufferedWriter(fw); ThreadLocalRandom random = ThreadLocalRandom.current(); for (int i = 1; i < quantity; i++) { bw.write(String.valueOf(random.nextInt(1, quantity * 5)) + " "); } bw.write( String.valueOf( random.nextInt(1, quantity * 5))); // nach der letzten Zahl folgt kein Space System.err.println("Die Datei " + filename + ".dat wurde erfolgreich erstellt"); } catch (IOException e) { e.printStackTrace(); } finally { try { bw.close(); } catch (IOException e) { e.printStackTrace(); } } } }
/** * Spins/yields/blocks until node s is matched or caller gives up. * * @param s the waiting node * @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 Message awaitMatch(Node s, Node pred, Message e, boolean timed, long nanos) throws SuspendExecution { long lastTime = timed ? System.nanoTime() : 0L; Strand w = Strand.currentStrand(); int spins = (w.isFiber() ? 0 : -1); // no spins in fiber; otherwise, initialized after first item and cancel checks ThreadLocalRandom randomYields = null; // bound if needed if (spins == 0) requestUnpark(s, w); for (; ; ) { Object item = s.item; if (item == CHANNEL_CLOSED) setReceiveClosed(); if (item != e) { // matched // assert item != s; s.forgetContents(); // avoid garbage return this.<Message>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) Strand.yield(); // occasionally yield } else if (s.waiter == null) { requestUnpark(s, w); // request unpark then recheck } else if (timed) { long now = System.nanoTime(); if ((nanos -= now - lastTime) > 0) Strand.parkNanos(this, nanos); lastTime = now; } else { Strand.park(this); } } }
public void run() { RateLimiter rl = rateLimit != 0 ? RateLimiter.create(rateLimit) : null; final ThreadLocalRandom tlr = ThreadLocalRandom.current(); while (!stop) { if (rl != null) rl.acquire(); String ks = KEYSPACE; ByteBuffer key = randomBytes(16, tlr); UpdateBuilder builder = UpdateBuilder.create(Schema.instance.getCFMetaData(KEYSPACE, TABLE), Util.dk(key)); for (int ii = 0; ii < numCells; ii++) { int sz = randomSize ? tlr.nextInt(cellSize) : cellSize; ByteBuffer bytes = randomBytes(sz, tlr); builder.newRow(CommitLogUpgradeTest.CELLNAME + ii).add("val", bytes); hash = hash(hash, bytes); ++cells; dataSize += sz; } rp = commitLog.add((Mutation) builder.makeMutation()); counter.incrementAndGet(); } }
RandomSelection select(boolean narrow, boolean mixInNotPresentItems, boolean permitReversal) { ThreadLocalRandom random = ThreadLocalRandom.current(); NavigableSet<Integer> canonicalSet = this.canonical; BTreeSet<Integer> testAsSet = this.test; List<Integer> canonicalList = new ArrayList<>(canonicalSet); BTreeSet<Integer> testAsList = this.test; Assert.assertEquals(canonicalSet.size(), testAsSet.size()); Assert.assertEquals(canonicalList.size(), testAsList.size()); // sometimes select keys first, so we cover full range List<Integer> allKeys = randomKeys(canonical, mixInNotPresentItems); List<Integer> keys = allKeys; int narrowCount = random.nextInt(3); while (narrow && canonicalList.size() > 10 && keys.size() > 10 && narrowCount-- > 0) { boolean useLb = random.nextBoolean(); boolean useUb = random.nextBoolean(); if (!(useLb | useUb)) continue; // select a range smaller than the total span when we have more narrowing iterations left int indexRange = keys.size() / (narrowCount + 1); boolean lbInclusive = true; Integer lbKey = canonicalList.get(0); int lbKeyIndex = 0, lbIndex = 0; boolean ubInclusive = true; Integer ubKey = canonicalList.get(canonicalList.size() - 1); int ubKeyIndex = keys.size(), ubIndex = canonicalList.size(); if (useLb) { lbKeyIndex = random.nextInt(0, indexRange - 1); Integer candidate = keys.get(lbKeyIndex); if (useLb = (candidate > lbKey && candidate <= ubKey)) { lbInclusive = random.nextBoolean(); lbKey = keys.get(lbKeyIndex); lbIndex = Collections.binarySearch(canonicalList, lbKey); if (lbIndex >= 0 && !lbInclusive) lbIndex++; else if (lbIndex < 0) lbIndex = -1 - lbIndex; } } if (useUb) { ubKeyIndex = random.nextInt(Math.max(lbKeyIndex, keys.size() - indexRange), keys.size() - 1); Integer candidate = keys.get(ubKeyIndex); if (useUb = (candidate < ubKey && candidate >= lbKey)) { ubInclusive = random.nextBoolean(); ubKey = keys.get(ubKeyIndex); ubIndex = Collections.binarySearch(canonicalList, ubKey); if (ubIndex >= 0 && ubInclusive) { ubIndex++; } else if (ubIndex < 0) ubIndex = -1 - ubIndex; } } if (ubIndex < lbIndex) { ubIndex = lbIndex; ubKey = lbKey; ubInclusive = false; } canonicalSet = !useLb ? canonicalSet.headSet(ubKey, ubInclusive) : !useUb ? canonicalSet.tailSet(lbKey, lbInclusive) : canonicalSet.subSet(lbKey, lbInclusive, ubKey, ubInclusive); testAsSet = !useLb ? testAsSet.headSet(ubKey, ubInclusive) : !useUb ? testAsSet.tailSet(lbKey, lbInclusive) : testAsSet.subSet(lbKey, lbInclusive, ubKey, ubInclusive); keys = keys.subList(lbKeyIndex, ubKeyIndex); canonicalList = canonicalList.subList(lbIndex, ubIndex); testAsList = testAsList.subList(lbIndex, ubIndex); Assert.assertEquals(canonicalSet.size(), testAsSet.size()); Assert.assertEquals(canonicalList.size(), testAsList.size()); } // possibly restore full set of keys, to test case where we are provided existing keys that // are out of bounds if (keys != allKeys && random.nextBoolean()) keys = allKeys; Comparator<Integer> comparator = naturalOrder(); if (permitReversal && random.nextBoolean()) { if (allKeys != keys) keys = new ArrayList<>(keys); if (canonicalSet != canonical) canonicalList = new ArrayList<>(canonicalList); Collections.reverse(keys); Collections.reverse(canonicalList); testAsList = testAsList.descendingSet(); canonicalSet = canonicalSet.descendingSet(); testAsSet = testAsSet.descendingSet(); comparator = reverseOrder(); } Assert.assertEquals(canonicalSet.size(), testAsSet.size()); Assert.assertEquals(canonicalList.size(), testAsList.size()); if (!canonicalSet.isEmpty()) { Assert.assertEquals(canonicalSet.first(), canonicalList.get(0)); Assert.assertEquals(canonicalSet.last(), canonicalList.get(canonicalList.size() - 1)); Assert.assertEquals(canonicalSet.first(), testAsSet.first()); Assert.assertEquals(canonicalSet.last(), testAsSet.last()); Assert.assertEquals(canonicalSet.first(), testAsList.get(0)); Assert.assertEquals(canonicalSet.last(), testAsList.get(testAsList.size() - 1)); } return new RandomSelection( keys, canonicalSet, testAsSet, canonicalList, testAsList, comparator); }
private int[] createRandomItems(int size) { return IntStream.range(0, size).mapToObj(i -> random.nextInt(3)).mapToInt(i -> i).toArray(); }