java.util.concurrent.ThreadLocalRandom Java Examples

The following examples show how to use java.util.concurrent.ThreadLocalRandom. 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 File: TalismanListener.java    From Slimefun4 with GNU General Public License v3.0 6 votes vote down vote up
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void onBlockBreak(BlockBreakEvent e) {
    ItemStack item = e.getPlayer().getInventory().getItemInMainHand();

    if (item.getType() != Material.AIR && item.getAmount() > 0) {
        List<ItemStack> drops = new ArrayList<>(e.getBlock().getDrops(item));
        int dropAmount = 1;

        if (item.getEnchantments().containsKey(Enchantment.LOOT_BONUS_BLOCKS) && !item.getEnchantments().containsKey(Enchantment.SILK_TOUCH)) {
            Random random = ThreadLocalRandom.current();
            dropAmount = random.nextInt(item.getEnchantmentLevel(Enchantment.LOOT_BONUS_BLOCKS) + 2) - 1;
            dropAmount = Math.max(dropAmount, 1);
            dropAmount = (e.getBlock().getType() == Material.LAPIS_ORE ? 4 + random.nextInt(5) : 1) * (dropAmount + 1);
        }

        if (!item.getEnchantments().containsKey(Enchantment.SILK_TOUCH) && MaterialCollections.getAllOres().contains(e.getBlock().getType()) && Talisman.checkFor(e, SlimefunItems.TALISMAN_MINER)) {
            for (ItemStack drop : drops) {
                if (!drop.getType().isBlock()) {
                    int amount = Math.max(1, (dropAmount * 2) - drop.getAmount());
                    e.getBlock().getWorld().dropItemNaturally(e.getBlock().getLocation(), new CustomItem(drop, amount));
                }
            }
        }
    }
}
 
Example #2
Source File: PinotSegmentUtil.java    From incubator-pinot with Apache License 2.0 6 votes vote down vote up
public static List<GenericRow> createTestData(Schema schema, int numRows) {
  List<GenericRow> rows = new ArrayList<>();
  final ThreadLocalRandom random = ThreadLocalRandom.current();
  Map<String, Object> fields;
  for (int i = 0; i < numRows; i++) {
    fields = new HashMap<>();
    for (FieldSpec fieldSpec : schema.getAllFieldSpecs()) {
      Object value;
      if (fieldSpec.isSingleValueField()) {
        value = generateSingleValue(random, fieldSpec);
      } else {
        value = generateMultiValue(random, fieldSpec);
      }
      fields.put(fieldSpec.getName(), value);
    }
    GenericRow row = new GenericRow();
    row.init(fields);
    rows.add(row);
  }
  return rows;
}
 
Example #3
Source File: IgniteSqlSkipReducerOnUpdateDmlSelfTest.java    From ignite with Apache License 2.0 6 votes vote down vote up
/**
 * Produces all possible combinations.
 *
 * @param a First array.
 * @param b Second array.
 * @param ends Endings array.
 * @return Result.
 */
private List<String> produceCombination(String[] a, String[] b, String[] ends) {
    List<String> res = new ArrayList<>();

    for (String s1 : a) {
        for (String s2 : b) {
            if (!s1.equals(s2)) {
                String end = ends[ThreadLocalRandom.current().nextInt(ends.length)];

                res.add(s1 + " " + s2 + end);
            }
        }
    }

    return res;
}
 
Example #4
Source File: ProcessTaskTest.java    From amazon-kinesis-client with Apache License 2.0 6 votes vote down vote up
private KinesisClientRecord createAndRegisterAggregatedRecord(BigInteger sequenceNumber,
        AggregatedRecord.Builder aggregatedRecord, int i, Instant approximateArrivalTime) {
    byte[] dataArray = new byte[1024];
    ThreadLocalRandom.current().nextBytes(dataArray);
    ByteBuffer data = ByteBuffer.wrap(dataArray);

    KinesisClientRecord expectedRecord = KinesisClientRecord.builder().partitionKey("p-" + i)
            .sequenceNumber(sequenceNumber.toString()).approximateArrivalTimestamp(approximateArrivalTime)
            .data(data).subSequenceNumber(i).aggregated(true).build();

    Messages.Record kplRecord = Messages.Record.newBuilder().setData(ByteString.copyFrom(dataArray))
            .setPartitionKeyIndex(i).build();
    aggregatedRecord.addPartitionKeyTable(expectedRecord.partitionKey()).addRecords(kplRecord);

    return expectedRecord;
}
 
Example #5
Source File: Receiver.java    From tutorials with MIT License 6 votes vote down vote up
public void run() {
    for(String receivedMessage = load.receive();
      !"End".equals(receivedMessage) ;
      receivedMessage = load.receive()) {
        
        System.out.println(receivedMessage);

        //Thread.sleep() to mimic heavy server-side processing
        try {
            Thread.sleep(ThreadLocalRandom.current().nextInt(1000, 5000));
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt(); 
            System.out.println("Thread Interrupted");
        }
    }
}
 
Example #6
Source File: ThreadLocalRandomTest.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * nextInt(bound) returns 0 <= value < bound; repeated calls produce at
 * least two distinct results
 */
public void testNextIntBounded() {
    // sample bound space across prime number increments
    for (int bound = 2; bound < MAX_INT_BOUND; bound += 524959) {
        int f = ThreadLocalRandom.current().nextInt(bound);
        assertTrue(0 <= f && f < bound);
        int i = 0;
        int j;
        while (i < NCALLS &&
               (j = ThreadLocalRandom.current().nextInt(bound)) == f) {
            assertTrue(0 <= j && j < bound);
            ++i;
        }
        assertTrue(i < NCALLS);
    }
}
 
Example #7
Source File: RocksDBWriteBatchWrapperTest.java    From flink with Apache License 2.0 6 votes vote down vote up
/**
 * Tests that {@link RocksDBWriteBatchWrapper} flushes after the kv count exceeds the preconfigured value.
 */
@Test
public void testWriteBatchWrapperFlushAfterCountExceed() throws Exception {
	try (RocksDB db = RocksDB.open(folder.newFolder().getAbsolutePath());
		WriteOptions options = new WriteOptions().setDisableWAL(true);
		ColumnFamilyHandle handle = db.createColumnFamily(new ColumnFamilyDescriptor("test".getBytes()));
		RocksDBWriteBatchWrapper writeBatchWrapper = new RocksDBWriteBatchWrapper(db, options, 100, 50000)) {
		long initBatchSize = writeBatchWrapper.getDataSize();
		byte[] dummy = new byte[2];
		ThreadLocalRandom.current().nextBytes(dummy);
		for (int i = 1; i < 100; ++i) {
			writeBatchWrapper.put(handle, dummy, dummy);
			// each kv consumes 8 bytes
			assertEquals(initBatchSize + 8 * i, writeBatchWrapper.getDataSize());
		}
		writeBatchWrapper.put(handle, dummy, dummy);
		assertEquals(initBatchSize, writeBatchWrapper.getDataSize());
	}
}
 
Example #8
Source File: AppendEntriesBenchmark.java    From sofa-jraft with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) throws RunnerException {
    final int size = ThreadLocalRandom.current().nextInt(100, 1000);
    System.out.println(sendEntries1(256, size).length);
    System.out.println(sendEntries2(256, size).length);
    System.out.println(sendEntries3(256, size, AdaptiveBufAllocator.DEFAULT.newHandle()).length);
    System.out.println(sendEntries4(256, size).length);

    Options opt = new OptionsBuilder() //
        .include(AppendEntriesBenchmark.class.getSimpleName()) //
        .warmupIterations(1) //
        .warmupTime(TimeValue.seconds(5)) //
        .measurementIterations(3) //
        .measurementTime(TimeValue.seconds(10)) //
        .threads(8) //
        .forks(1) //
        .build();

    new Runner(opt).run();
}
 
Example #9
Source File: IByteArrayCodecTest.java    From ph-commons with Apache License 2.0 6 votes vote down vote up
private void _testCodec (@Nonnull final IByteArrayCodec c)
{
  _testCodec (c, ArrayHelper.EMPTY_BYTE_ARRAY);
  _testCodec (c, "Hallo JÜnit".getBytes (StandardCharsets.ISO_8859_1));
  _testCodec (c, "Hallo JÜnit".getBytes (StandardCharsets.UTF_8));

  // Get random bytes
  final byte [] aRandomBytes = new byte [256];
  ThreadLocalRandom.current ().nextBytes (aRandomBytes);
  _testCodec (c, aRandomBytes);

  for (int i = 0; i < 256; ++i)
  {
    final byte [] aBuf = new byte [i];

    // build ascending identity field
    for (int j = 0; j < i; ++j)
      aBuf[j] = (byte) j;
    _testCodec (c, aBuf);

    // build constant field with all the same byte
    for (int j = 0; j < i; ++j)
      aBuf[j] = (byte) i;
    _testCodec (c, aBuf);
  }
}
 
Example #10
Source File: TestPubsubSignal.java    From beam with Apache License 2.0 6 votes vote down vote up
/** Wait for a success signal for {@code duration}. */
public void waitForSuccess(Duration duration) throws IOException {
  SubscriptionPath resultSubscriptionPath =
      PubsubClient.subscriptionPathFromName(
          pipelineOptions.getProject(),
          "result-subscription-" + String.valueOf(ThreadLocalRandom.current().nextLong()));

  pubsub.createSubscription(
      resultTopicPath, resultSubscriptionPath, (int) duration.getStandardSeconds());

  String result = pollForResultForDuration(resultSubscriptionPath, duration);

  if (!RESULT_SUCCESS_MESSAGE.equals(result)) {
    throw new AssertionError(result);
  }
}
 
Example #11
Source File: KafkaTest.java    From replicator with Apache License 2.0 6 votes vote down vote up
private static AugmentedEvent getAugmentedEvent(int index) {
    byte[] data = new byte[100];

    ThreadLocalRandom.current().nextBytes(data);

    return new AugmentedEvent(
            new AugmentedEventHeader(
                    System.currentTimeMillis(),
                    KafkaTest.getCheckpoint(index),
                    AugmentedEventType.BYTE_ARRAY,
                    "dbName",
                    "tableName"
            ),
            new ByteArrayAugmentedEventData(AugmentedEventType.BYTE_ARRAY, data)
    );
}
 
Example #12
Source File: TransformerTest.java    From apicurio-registry with Apache License 2.0 6 votes vote down vote up
@Test
public void testType() {
    ByteBuffer buffer = ByteBuffer.allocate(30);
    buffer.put((byte) 0x0);
    buffer.putInt(42);
    byte[] bytes = new byte[25];
    ThreadLocalRandom.current().nextBytes(bytes);
    buffer.put(bytes);

    byte[] input = buffer.array();
    byte[] output = Transformer.Type.CONFLUENT_TO_APICURIO.apply(input);
    byte[] copy = Transformer.Type.APICURIO_TO_CONFLUENT.apply(output);
    Assertions.assertArrayEquals(input, copy);

    buffer = ByteBuffer.allocate(30);
    buffer.put((byte) 0x0);
    buffer.putLong(42L);
    bytes = new byte[21];
    ThreadLocalRandom.current().nextBytes(bytes);
    buffer.put(bytes);

    input = buffer.array();
    output = Transformer.Type.APICURIO_TO_CONFLUENT.apply(input);
    copy = Transformer.Type.CONFLUENT_TO_APICURIO.apply(output);
    Assertions.assertArrayEquals(input, copy);
}
 
Example #13
Source File: BackoffRetryPolicy.java    From presto with Apache License 2.0 6 votes vote down vote up
@Override
public RetryDecision onUnavailable(Statement statement, ConsistencyLevel consistencyLevel, int requiredReplica, int aliveReplica, int retries)
{
    if (retries >= 10) {
        return RetryDecision.rethrow();
    }

    try {
        int jitter = ThreadLocalRandom.current().nextInt(100);
        int delay = (100 * (retries + 1)) + jitter;
        Thread.sleep(delay);
        return RetryDecision.retry(consistencyLevel);
    }
    catch (InterruptedException e) {
        Thread.currentThread().interrupt();
        return RetryDecision.rethrow();
    }
}
 
Example #14
Source File: RandomWeightLoadBalance.java    From eagle with Apache License 2.0 5 votes vote down vote up
@Override
public Refer<T> doSelect(Request request) {
    int length = refers.size(); // 总个数
    int totalWeight = 0; // 总权重
    boolean sameWeight = true; // 权重是否都一样
    for (int i = 0; i < length; i++) {
        int weight = getWeight(refers.get(i));
        totalWeight += weight; // 累计总权重
        if (sameWeight && i > 0 && weight != getWeight(refers.get(i - 1))) {
            sameWeight = false; // 计算所有权重是否一样
        }
    }
    if (totalWeight > 0 && !sameWeight) {
        // 如果权重不相同且权重大于0则按总权重数随机
        int offset = ThreadLocalRandom.current().nextInt(totalWeight);
        // 并确定随机值落在哪个片断上
        for (int i = 0; i < length; i++) {
            Refer<T> refer = refers.get(i);
            offset -= getWeight(refer);
            if (offset < 0 && refer.isAlive()) {
                return refer;
            }
        }
    }
    // 如果权重相同或权重为0则均等随机
    int idx = ThreadLocalRandom.current().nextInt(length);
    for (int i = 0; i < refers.size(); i++) {
        Refer<T> ref = refers.get((i + idx) % refers.size());
        if (ref.isAlive()) {
            return ref;
        }
    }
    return null;
}
 
Example #15
Source File: TestDriftClient.java    From drift with Apache License 2.0 5 votes vote down vote up
private static void assertNormalInvocation(
        ResultsSupplier resultsSupplier,
        Collection<Supplier<InvokeRequest>> targets,
        TestingMethodInvocationStatsFactory statsFactory,
        List<TestingExceptionClassifier> classifiers,
        Client client,
        Optional<String> qualifier)
        throws Exception
{
    resultsSupplier.setSuccessResult("result");

    TestingMethodInvocationStat stat = statsFactory.getStat("clientService", qualifier, "test");
    stat.clear();
    int invocationId = ThreadLocalRandom.current().nextInt();
    assertEquals(client.test(invocationId, "normal"), "result");
    verifyMethodInvocation(targets, "test", invocationId, "normal");
    classifiers.forEach(TestingExceptionClassifier::assertNoException);
    stat.assertSuccess(0);

    stat = statsFactory.getStat("clientService", qualifier, "testAsync");
    stat.clear();
    invocationId = ThreadLocalRandom.current().nextInt();
    assertEquals(client.testAsync(invocationId, "normal").get(), "result");
    verifyMethodInvocation(targets, "testAsync", invocationId, "normal");
    classifiers.forEach(TestingExceptionClassifier::assertNoException);
    stat.assertSuccess(0);

    stat = statsFactory.getStat("clientService", qualifier, "testHeader");
    stat.clear();
    invocationId = ThreadLocalRandom.current().nextInt();
    assertEquals(client.testHeader("headerValueA", invocationId, "headerValueB", "normal"), "result");
    verifyMethodInvocation(targets, "testHeader", invocationId, "normal", ImmutableMap.<String, String>builder()
            .putAll(HEADERS)
            .put("headerA", "headerValueA")
            .put("headerB", "headerValueB")
            .build());
    classifiers.forEach(TestingExceptionClassifier::assertNoException);
    stat.assertSuccess(0);
}
 
Example #16
Source File: PageEvictionMultinodeAbstractTest.java    From ignite with Apache License 2.0 5 votes vote down vote up
/**
 * @param cfg Config.
 * @throws Exception If failed.
 */
protected void createCacheAndTestEviction(CacheConfiguration<Object, Object> cfg) throws Exception {
    IgniteCache<Object, Object> cache = clientGrid().getOrCreateCache(cfg);

    for (int i = 1; i <= ENTRIES; i++) {
        ThreadLocalRandom r = ThreadLocalRandom.current();

        if (r.nextInt() % 5 == 0)
            cache.put(i, new TestObject(PAGE_SIZE / 4 - 50 + r.nextInt(5000))); // Fragmented object.
        else
            cache.put(i, new TestObject(r.nextInt(PAGE_SIZE / 4 - 50))); // Fits in one page.

        if (r.nextInt() % 7 == 0)
            cache.get(r.nextInt(i)); // Touch.
        else if (r.nextInt() % 11 == 0)
            cache.remove(r.nextInt(i)); // Remove.
        else if (r.nextInt() % 13 == 0)
            cache.put(r.nextInt(i), new TestObject(r.nextInt(PAGE_SIZE / 2))); // Update.

        if (i % (ENTRIES / 10) == 0)
            System.out.println(">>> Entries put: " + i);
    }

    int resultingSize = cache.size(CachePeekMode.PRIMARY);

    System.out.println(">>> Resulting size: " + resultingSize);

    // Eviction started, no OutOfMemory occurred, success.
    assertTrue(resultingSize < ENTRIES * 10 / 11);

    clientGrid().destroyCache(cfg.getName());
}
 
Example #17
Source File: TimerWheelBenchmark.java    From caffeine with Apache License 2.0 5 votes vote down vote up
@Setup
public void setup() {
  timer = new Timer(0);
  times = new long[SIZE];
  timerWheel = new TimerWheel<>(new MockCache());
  for (int i = 0; i < SIZE; i++) {
    times[i] = ThreadLocalRandom.current().nextLong(UPPERBOUND);
    timerWheel.schedule(new Timer(times[i]));
  }
  timerWheel.schedule(timer);
}
 
Example #18
Source File: BigInteger.java    From openjdk-8 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Returns true iff this BigInteger passes the specified number of
 * Miller-Rabin tests. This test is taken from the DSA spec (NIST FIPS
 * 186-2).
 *
 * The following assumptions are made:
 * This BigInteger is a positive, odd number greater than 2.
 * iterations<=50.
 */
private boolean passesMillerRabin(int iterations, Random rnd) {
    // Find a and m such that m is odd and this == 1 + 2**a * m
    BigInteger thisMinusOne = this.subtract(ONE);
    BigInteger m = thisMinusOne;
    int a = m.getLowestSetBit();
    m = m.shiftRight(a);

    // Do the tests
    if (rnd == null) {
        rnd = ThreadLocalRandom.current();
    }
    for (int i=0; i < iterations; i++) {
        // Generate a uniform random on (1, this)
        BigInteger b;
        do {
            b = new BigInteger(this.bitLength(), rnd);
        } while (b.compareTo(ONE) <= 0 || b.compareTo(this) >= 0);

        int j = 0;
        BigInteger z = b.modPow(m, this);
        while (!((j == 0 && z.equals(ONE)) || z.equals(thisMinusOne))) {
            if (j > 0 && z.equals(ONE) || ++j == a)
                return false;
            z = z.modPow(TWO, this);
        }
    }
    return true;
}
 
Example #19
Source File: WorldController.java    From FrameworkBenchmarks with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@GetAction("queries")
public final World[] multipleQueries(String queries) {
    int q = regulateQueries(queries);

    World[] worlds = ThreadLocalRandom
        .current()
        .ints(1, WORLD_MAX_ROW + 1)
        .distinct()
        .limit(q)
        .mapToObj(id -> dao.findById(id))
        .toArray(World[]::new);
    return worlds;
}
 
Example #20
Source File: SliceUtf8Benchmark.java    From slice with Apache License 2.0 5 votes vote down vote up
@Setup
public void setup()
{
    int[] codePointSet = ascii ? ASCII_CODE_POINTS : ALL_CODE_POINTS;
    ThreadLocalRandom random = ThreadLocalRandom.current();

    codePoints = new int[length];
    DynamicSliceOutput sliceOutput = new DynamicSliceOutput(length * 4);
    for (int i = 0; i < codePoints.length; i++) {
        int codePoint = codePointSet[random.nextInt(codePointSet.length)];
        codePoints[i] = codePoint;
        sliceOutput.appendBytes(new String(Character.toChars(codePoint)).getBytes(StandardCharsets.UTF_8));
    }
    slice = sliceOutput.slice();
}
 
Example #21
Source File: SystemUtils.java    From latexdraw with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Creates a temporary directory that will be used to contains temporary files.
 * The created folder will have restricted access: only the user can access the folder.
 * @return The created folder or null (if the folder cannot be created or the rights cannot be restricted to the current user).
 */
public @NotNull Optional<File> createTempDir() {
	try {
		return Optional.of(
			Files
				.createTempDirectory("latexdrawTmp" + System.currentTimeMillis() + ThreadLocalRandom.current().nextInt(100000)) //NON-NLS
				.toFile());
	}catch(final IOException | SecurityException ex) {
		BadaboomCollector.INSTANCE.add(ex);
		return Optional.empty();
	}
}
 
Example #22
Source File: BenchmarkGroupByHash.java    From presto with Apache License 2.0 5 votes vote down vote up
private static List<Page> createVarcharPages(int positionCount, int groupCount, int channelCount, boolean hashEnabled)
{
    List<Type> types = Collections.nCopies(channelCount, VARCHAR);
    ImmutableList.Builder<Page> pages = ImmutableList.builder();
    if (hashEnabled) {
        types = ImmutableList.copyOf(Iterables.concat(types, ImmutableList.of(BIGINT)));
    }

    PageBuilder pageBuilder = new PageBuilder(types);
    for (int position = 0; position < positionCount; position++) {
        int rand = ThreadLocalRandom.current().nextInt(groupCount);
        Slice value = Slices.wrappedBuffer(ByteBuffer.allocate(4).putInt(rand));
        pageBuilder.declarePosition();
        for (int channel = 0; channel < channelCount; channel++) {
            VARCHAR.writeSlice(pageBuilder.getBlockBuilder(channel), value);
        }
        if (hashEnabled) {
            BIGINT.writeLong(pageBuilder.getBlockBuilder(channelCount), VarcharOperators.hashCode(value));
        }
        if (pageBuilder.isFull()) {
            pages.add(pageBuilder.build());
            pageBuilder.reset();
        }
    }
    pages.add(pageBuilder.build());
    return pages.build();
}
 
Example #23
Source File: ForkJoinPool.java    From openjdk-8 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Returns common pool queue for a thread that has submitted at
 * least one task.
 */
static WorkQueue commonSubmitterQueue() {
    ForkJoinPool p; WorkQueue[] ws; int m, z;
    return ((z = ThreadLocalRandom.getProbe()) != 0 &&
            (p = common) != null &&
            (ws = p.workQueues) != null &&
            (m = ws.length - 1) >= 0) ?
        ws[m & z & SQMASK] : null;
}
 
Example #24
Source File: MultiThreadedClientExample.java    From hbase with Apache License 2.0 5 votes vote down vote up
@Override
public Boolean call() throws Exception {

  // Table implements Closable so we use the try with resource structure here.
  // https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html
  try (Table t = connection.getTable(tableName)) {
    byte[] value = Bytes.toBytes(Double.toString(ThreadLocalRandom.current().nextDouble()));
    int rows = 30;

    // Array to put the batch
    ArrayList<Put> puts = new ArrayList<>(rows);
    for (int i = 0; i < 30; i++) {
      byte[] rk = Bytes.toBytes(ThreadLocalRandom.current().nextLong());
      Put p = new Put(rk);
      p.add(CellBuilderFactory.create(CellBuilderType.SHALLOW_COPY)
            .setRow(rk)
            .setFamily(FAMILY)
            .setQualifier(QUAL)
            .setTimestamp(p.getTimestamp())
            .setType(Cell.Type.Put)
            .setValue(value)
            .build());
      puts.add(p);
    }

    // now that we've assembled the batch it's time to push it to hbase.
    t.put(puts);
  }
  return true;
}
 
Example #25
Source File: PaymentTest.java    From africastalking-java with MIT License 5 votes vote down vote up
@Test
public void testCardCheckout() throws IOException {
    PaymentService service = AfricasTalking.getService(PaymentService.class);
    PaymentCard card = new PaymentCard("4223372036854775807", 1232, 10, 2022, "NG", "0022");
    CheckoutResponse resp = service.cardCheckoutCharge("TestProduct", "KES", ThreadLocalRandom.current().nextInt(200, 15001), card, "Test card checkout?", new HashMap());
    Assert.assertEquals(Status.PENDING_VALIDATION, resp.status);
}
 
Example #26
Source File: TracingMetadataCodecTest.java    From rsocket-java with Apache License 2.0 5 votes vote down vote up
@ParameterizedTest
@MethodSource("flags")
public void shouldEncodeTrace64(TracingMetadataCodec.Flags expectedFlag) {
  long traceId = ThreadLocalRandom.current().nextLong();
  long spanId = ThreadLocalRandom.current().nextLong();
  LeaksTrackingByteBufAllocator allocator =
      LeaksTrackingByteBufAllocator.instrument(ByteBufAllocator.DEFAULT);
  ByteBuf byteBuf = TracingMetadataCodec.encode64(allocator, traceId, spanId, expectedFlag);

  TracingMetadata tracingMetadata = TracingMetadataCodec.decode(byteBuf);

  Assertions.assertThat(tracingMetadata)
      .matches(metadata -> !metadata.isEmpty())
      .matches(tm -> tm.traceIdHigh() == 0)
      .matches(tm -> tm.traceId() == traceId)
      .matches(tm -> tm.spanId() == spanId)
      .matches(tm -> !tm.hasParent())
      .matches(tm -> tm.parentId() == 0)
      .matches(
          tm -> {
            switch (expectedFlag) {
              case UNDECIDED:
                return !tm.isDecided();
              case NOT_SAMPLE:
                return tm.isDecided() && !tm.isSampled();
              case SAMPLE:
                return tm.isDecided() && tm.isSampled();
              case DEBUG:
                return tm.isDecided() && tm.isDebug();
            }
            return false;
          });
  Assertions.assertThat(byteBuf).matches(ReferenceCounted::release);
  allocator.assertHasNoLeaks();
}
 
Example #27
Source File: Level.java    From Nukkit with GNU General Public License v3.0 5 votes vote down vote up
public boolean setThundering(boolean thundering) {
    ThunderChangeEvent ev = new ThunderChangeEvent(this, thundering);
    this.getServer().getPluginManager().callEvent(ev);

    if (ev.isCancelled()) {
        return false;
    }

    if (thundering && !isRaining()) {
        setRaining(true);
    }

    this.thundering = thundering;

    LevelEventPacket pk = new LevelEventPacket();
    // These numbers are from Minecraft
    if (thundering) {
        pk.evid = LevelEventPacket.EVENT_START_THUNDER;
        pk.data = ThreadLocalRandom.current().nextInt(50000) + 10000;
        setThunderTime(ThreadLocalRandom.current().nextInt(12000) + 3600);
    } else {
        pk.evid = LevelEventPacket.EVENT_STOP_THUNDER;
        setThunderTime(ThreadLocalRandom.current().nextInt(168000) + 12000);
    }

    Server.broadcastPacket(this.getPlayers().values(), pk);

    return true;
}
 
Example #28
Source File: TestShardOrganizerUtil.java    From presto with Apache License 2.0 5 votes vote down vote up
@BeforeMethod
public void setup()
{
    dbi = new DBI("jdbc:h2:mem:test" + System.nanoTime() + ThreadLocalRandom.current().nextLong());
    dbi.registerMapper(new TableColumn.Mapper(new InternalTypeManager(createTestMetadataManager())));
    dummyHandle = dbi.open();
    createTablesWithRetry(dbi);
    dataDir = Files.createTempDir();

    metadata = new RaptorMetadata(dbi, createShardManager(dbi));

    metadataDao = dbi.onDemand(MetadataDao.class);
    shardManager = createShardManager(dbi);
}
 
Example #29
Source File: ThreadLocalRandomTest.java    From openjdk-8-source with GNU General Public License v2.0 5 votes vote down vote up
/**
 * A parallel unsized stream of doubles generates at least 100 values
 */
public void testUnsizedDoublesCount() {
    LongAdder counter = new LongAdder();
    ThreadLocalRandom r = ThreadLocalRandom.current();
    long size = 100;
    r.doubles().limit(size).parallel().forEach(x -> {
        counter.increment();
    });
    assertEquals(counter.sum(), size);
}
 
Example #30
Source File: PetData.java    From aws-serverless-java-container with Apache License 2.0 5 votes vote down vote up
public Date getRandomDoB() {
    GregorianCalendar gc = new GregorianCalendar();

    int year = ThreadLocalRandom.current().nextInt(
            Calendar.getInstance().get(Calendar.YEAR) - 15,
            Calendar.getInstance().get(Calendar.YEAR)
    );

    gc.set(Calendar.YEAR, year);

    int dayOfYear = ThreadLocalRandom.current().nextInt(1, gc.getActualMaximum(Calendar.DAY_OF_YEAR));

    gc.set(Calendar.DAY_OF_YEAR, dayOfYear);
    return gc.getTime();
}