Java Code Examples for java.util.concurrent.ThreadLocalRandom#nextBytes()

The following examples show how to use java.util.concurrent.ThreadLocalRandom#nextBytes() . These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: dremio-oss   File: ExternalIdHelper.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Helper method to generate an "external" QueryId.
 *
 * This is the only method that can generate external query Id.
 *
 * @return generated QueryId
 */
public static ExternalId generateExternalId() {
  ThreadLocalRandom r = ThreadLocalRandom.current();

  // create a new internalId where the first four bytes are a growing time (each new value comes earlier in sequence).
  // Last 11 bytes are random.
  // last byte is set to 0
  final long time = (int) (System.currentTimeMillis()/1000);
  final long p1 = ((Integer.MAX_VALUE - time) << 32) + r.nextInt();

  // generate a long from 7 random bytes + 1 zero byte
  // I could also just generate a random long then mask it's last bit
  // but not sure how this will affect it's randomness
  final byte[] bytes = new byte[7];
  r.nextBytes(bytes);
  long p2 = 0;
  for (int i = 0; i < 7; i++) {
    p2 += (bytes[i] & 0xFFL) << (8 * i);
  }
  p2 = p2 << 8;

  return ExternalId.newBuilder().setPart1(p1).setPart2(p2).build();
}
 
Example 2
Source Project: ignite   File: GridCommandHandlerTest.java    License: Apache License 2.0 6 votes vote down vote up
/** */
private void corruptPartition(File partitionsDir) throws IOException {
    ThreadLocalRandom rand = ThreadLocalRandom.current();

    for (File partFile : partitionsDir.listFiles((d, n) -> n.startsWith("part"))) {
        try (RandomAccessFile raf = new RandomAccessFile(partFile, "rw")) {
            byte[] buf = new byte[1024];

            rand.nextBytes(buf);

            raf.seek(4096 * 2 + 1);

            raf.write(buf);
        }
    }
}
 
Example 3
Source Project: flink   File: SkipListUtilsTest.java    License: Apache License 2.0 6 votes vote down vote up
private KeySpace createKeySpace(int level, int keyLen) {
	ThreadLocalRandom random = ThreadLocalRandom.current();
	KeySpace keySpace = new KeySpace();
	keySpace.level = level;
	keySpace.status = random.nextBoolean() ? NodeStatus.PUT : NodeStatus.REMOVE;
	keySpace.valuePointer = random.nextLong();
	keySpace.nextKeyPointer = random.nextLong();
	keySpace.nextIndexNodes = new long[level];
	keySpace.prevIndexNodes = new long[level];
	for (int i = 0; i < level; i++) {
		keySpace.nextIndexNodes[i] = random.nextLong();
		keySpace.prevIndexNodes[i] = random.nextLong();
	}
	keySpace.keyData = new byte[keyLen];
	random.nextBytes(keySpace.keyData);
	return keySpace;
}
 
Example 4
@Test
public void smokeTestRandomDataWithJdk() throws IOException
{
    GzipCompressionProvider provider = new GzipCompressionProvider();
    ThreadLocalRandom random = ThreadLocalRandom.current();
    for (int len = 1; len < 100; len++)
    {
        byte[] data = new byte[len];
        for (int i = 0; i < 100; i++) {
            byte[] compressedData = provider.compress(null, data);
            byte[] jdkCompressedData = jdkCompress(data);
            Assert.assertTrue(Arrays.equals(compressedData, jdkCompressedData));
            byte[] decompressedData = provider.decompress(null, compressedData);
            Assert.assertTrue(Arrays.equals(decompressedData, data));
            // in the end of the iteration to test empty array first
            random.nextBytes(data);
        }
    }
}
 
Example 5
Source Project: rocketmq   File: TransactionProducer.java    License: Apache License 2.0 5 votes vote down vote up
private static Message buildMessage(TxSendConfig config) {
    byte[] bs = new byte[config.messageSize];
    ThreadLocalRandom r = ThreadLocalRandom.current();
    r.nextBytes(bs);

    ByteBuffer buf = ByteBuffer.wrap(bs);
    buf.putLong(config.batchId);
    long sendMachineId = START_TIME << 32;
    long msgId = sendMachineId | MSG_COUNT.getAndIncrement();
    buf.putLong(msgId);

    // save send tx result in message
    if (r.nextDouble() < config.sendRollbackRate) {
        buf.put((byte) LocalTransactionState.ROLLBACK_MESSAGE.ordinal());
    } else if (r.nextDouble() < config.sendUnknownRate) {
        buf.put((byte) LocalTransactionState.UNKNOW.ordinal());
    } else {
        buf.put((byte) LocalTransactionState.COMMIT_MESSAGE.ordinal());
    }

    // save check tx result in message
    for (int i = 0; i < MAX_CHECK_RESULT_IN_MSG; i++) {
        if (r.nextDouble() < config.checkRollbackRate) {
            buf.put((byte) LocalTransactionState.ROLLBACK_MESSAGE.ordinal());
        } else if (r.nextDouble() < config.checkUnknownRate) {
            buf.put((byte) LocalTransactionState.UNKNOW.ordinal());
        } else {
            buf.put((byte) LocalTransactionState.COMMIT_MESSAGE.ordinal());
        }
    }

    Message msg = new Message();
    msg.setTopic(config.topic);

    msg.setBody(bs);
    return msg;
}
 
Example 6
/**
 * @param name The file name to create.
 * @param size The file size.
 * @throws IOException If fails.
 */
private File createFileRandomData(String name, final int size) throws IOException {
    ThreadLocalRandom rnd = ThreadLocalRandom.current();

    File out = new File(tempStore, name);

    try (RandomAccessFile raf = new RandomAccessFile(out, "rw")) {
        byte[] buf = new byte[size];
        rnd.nextBytes(buf);
        raf.write(buf);
    }

    return out;
}
 
Example 7
/**
 * Default constructor.
 */
public TestObject() {
    ThreadLocalRandom rnd = ThreadLocalRandom.current();

    id = rnd.nextLong();
    len = rnd.nextInt(32 * 1024);
    arr = new byte[len];

    rnd.nextBytes(arr);
}
 
Example 8
Source Project: datakernel   File: StreamLZ4Test.java    License: Apache License 2.0 5 votes vote down vote up
private static ByteBuf createRandomByteBuf() {
	ThreadLocalRandom random = ThreadLocalRandom.current();
	int offset = random.nextInt(10);
	int tail = random.nextInt(10);
	int len = random.nextInt(100);
	byte[] array = new byte[offset + len + tail];
	random.nextBytes(array);
	return ByteBuf.wrap(array, offset, offset + len);
}
 
Example 9
Source Project: flink   File: SkipListUtilsTest.java    License: Apache License 2.0 5 votes vote down vote up
private ValueSpace createValueSpace(int valueLen) {
	ThreadLocalRandom random = ThreadLocalRandom.current();
	ValueSpace valueSpace = new ValueSpace();
	valueSpace.version = random.nextInt(Integer.MAX_VALUE);
	valueSpace.keyPointer = random.nextLong();
	valueSpace.nextValuePointer = random.nextLong();
	valueSpace.valueData = new byte[valueLen];
	random.nextBytes(valueSpace.valueData);
	return valueSpace;
}
 
Example 10
/**
 * Write some random trash in index partition.
 */
private void corruptIndexPartition(File path, int size, int offset) throws IOException {
    assertTrue(path.exists());

    ThreadLocalRandom rand = ThreadLocalRandom.current();

    try (RandomAccessFile idx = new RandomAccessFile(path, "rw")) {
        byte[] trash = new byte[size];

        rand.nextBytes(trash);

        idx.seek(offset);

        idx.write(trash);
    }
}
 
Example 11
public void keySegmentDistributionTest(int size, int segments) {
    ChronicleMap<CharSequence, Integer> map = ChronicleMapBuilder
            .of(CharSequence.class, Integer.class)
            .actualSegments(segments)
            // TODO problems with computing proper number of segments/chunks
            // when I write this without `* 2` I expect not to have ISE "segment is full"...
            .entries(size * 2)
            .averageKeySize(10)
            .create();

    byte[] keyBytes = new byte[10];
    ThreadLocalRandom random = ThreadLocalRandom.current();
    for (int i = 0; i < size; i++) {
        random.nextBytes(keyBytes);
        String key = new String(keyBytes, StandardCharsets.US_ASCII);
        long hash = LongHashFunction.xx().hashBytes(StandardCharsets.UTF_8.encode(key));
        int segmentIndex = (((int) hash) & Integer.MAX_VALUE) % segments;
        // Put the segment index as a value to the map
        map.put(key, segmentIndex);
    }
    // The following loop checks that internally hash code and segment index is chosen
    // the same way as we explicitly computed in this test. Since ChMap iteration is segment
    // by segment, we expect to see the sequence of values 0, 0, ... 0, 1, ..1, 2, ..2, 3, ..3
    // or opposite -- 3, 3, ... 3, 2, ..2, 1, ..1, 0, ..0
    int currentSegment = -1;
    boolean ascendingDirection = false;
    for (Integer entrySegment : map.values()) {
        if (currentSegment == -1) {
            currentSegment = entrySegment;
            if (currentSegment == 0) {
                ascendingDirection = true;
            }
        } else {
            if (ascendingDirection) {
                Assert.assertTrue(entrySegment >= currentSegment);
                currentSegment = entrySegment;
            } else {
                // descending iteration direction
                Assert.assertTrue(entrySegment <= currentSegment);
                currentSegment = entrySegment;
            }
        }
    }
}