Java Code Examples for java.util.concurrent.ThreadLocalRandom

The following examples show how to use java.util.concurrent.ThreadLocalRandom. 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: apicurio-registry   Source File: TransformerTest.java    License: 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 2
Source Project: replicator   Source File: KafkaTest.java    License: 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 3
Source Project: presto   Source File: BackoffRetryPolicy.java    License: 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 4
Source Project: beam   Source File: TestPubsubSignal.java    License: 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 5
Source Project: sofa-jraft   Source File: AppendEntriesBenchmark.java    License: 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 6
Source Project: flink   Source File: RocksDBWriteBatchWrapperTest.java    License: 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 7
/**
 * 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 8
Source Project: ph-commons   Source File: IByteArrayCodecTest.java    License: 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 9
Source Project: tutorials   Source File: Receiver.java    License: 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 10
Source Project: incubator-pinot   Source File: PinotSegmentUtil.java    License: 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 11
/**
 * 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 12
Source Project: amazon-kinesis-client   Source File: ProcessTaskTest.java    License: 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 13
Source Project: Slimefun4   Source File: TalismanListener.java    License: 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 14
Source Project: presto   Source File: TestMetadataDao.java    License: Apache License 2.0 5 votes vote down vote up
@BeforeMethod
public void setup()
{
    IDBI dbi = new DBI("jdbc:h2:mem:test" + System.nanoTime() + ThreadLocalRandom.current().nextLong());
    dummyHandle = dbi.open();
    dao = dbi.onDemand(MetadataDao.class);
    createTablesWithRetry(dbi);
}
 
Example 15
Source Project: eagle   Source File: RandomWeightLoadBalance.java    License: 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 16
Source Project: dragonwell8_jdk   Source File: BigInteger.java    License: 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 17
public T dequeue() {
    while (true) {
        KSegment curHead = head.get();
        //iterate through the head segment to find a non-null element
        int startIndex = Math.abs(ThreadLocalRandom.current().nextInt()) % k;
        for (int i = 0; i <= k; i++) {
            T old_value = curHead.segment[(i + startIndex) % k].get();
            if (old_value == null) {
                continue;
            }
            if (curHead.segment[(i + startIndex) % k].compareAndSet(old_value, null)) {
                return old_value;
            }
        }
        // all elements were dequeued -> we can remove this segment, if it's not a single one
        KSegment curTail = tail.get();
        if (curHead != curTail) {
            head.compareAndSet(curHead, curHead.next.get());
        } else {
            if (curTail.next.get() != null) {
                tail.compareAndSet(curTail, curTail.next.get());
            } else {
                return null;
            }
        }
    }
}
 
Example 18
@Test
public void testSetSubspaceKeyCounter() {
    // Test setting the counter without enabling it
    MetaDataException e = assertThrows(MetaDataException.class, () -> RecordMetaData.newBuilder()
            .setRecords(TestRecords1Proto.getDescriptor())
            .setSubspaceKeyCounter(4L));
    assertEquals("Counter-based subspace keys not enabled", e.getMessage());

    // Test setting the counter to a value not greater than the current value
    e = assertThrows(MetaDataException.class, () -> RecordMetaData.newBuilder()
            .enableCounterBasedSubspaceKeys()
            .setRecords(TestRecords1Proto.getDescriptor())
            .setSubspaceKeyCounter(3L));
    assertEquals("Subspace key counter must be set to a value greater than its current value (3)", e.getMessage());

    // Set to a random number
    long randomCounter = ThreadLocalRandom.current().nextLong(1, Long.MAX_VALUE - 10);
    RecordMetaDataBuilder builder = RecordMetaData.newBuilder().enableCounterBasedSubspaceKeys().setSubspaceKeyCounter(randomCounter).setRecords(TestRecords1Proto.getDescriptor());
    RecordMetaData metaData = builder.build(true);
    assertNotNull(metaData.getIndex("MySimpleRecord$str_value_indexed"));
    assertNotNull(metaData.getIndex("MySimpleRecord$num_value_unique"));
    assertNotNull(metaData.getIndex("MySimpleRecord$num_value_3_indexed"));
    assertEquals(randomCounter + 1, metaData.getIndex("MySimpleRecord$str_value_indexed").getSubspaceKey());
    assertEquals(randomCounter + 2, metaData.getIndex("MySimpleRecord$num_value_unique").getSubspaceKey());
    assertEquals(randomCounter + 3, metaData.getIndex("MySimpleRecord$num_value_3_indexed").getSubspaceKey());

    // enable and set counter in the proto.
    RecordMetaDataProto.MetaData.Builder protoBuilder = RecordMetaDataProto.MetaData.newBuilder()
            .setRecords(TestRecords1Proto.getDescriptor().toProto());
    protoBuilder.setUsesSubspaceKeyCounter(true).setSubspaceKeyCounter(randomCounter);
    builder = RecordMetaData.newBuilder().setRecords(protoBuilder.build(), true);
    RecordMetaData metaDataFromProto = builder.build(true);
    assertNotNull(metaDataFromProto.getIndex("MySimpleRecord$str_value_indexed"));
    assertNotNull(metaDataFromProto.getIndex("MySimpleRecord$num_value_unique"));
    assertNotNull(metaDataFromProto.getIndex("MySimpleRecord$num_value_3_indexed"));
    assertEquals(randomCounter + 1, metaDataFromProto.getIndex("MySimpleRecord$str_value_indexed").getSubspaceKey());
    assertEquals(randomCounter + 2, metaDataFromProto.getIndex("MySimpleRecord$num_value_unique").getSubspaceKey());
    assertEquals(randomCounter + 3, metaDataFromProto.getIndex("MySimpleRecord$num_value_3_indexed").getSubspaceKey());
}
 
Example 19
Source Project: NeuralNetworkAPI   Source File: LogicalAND.java    License: GNU General Public License v3.0 5 votes vote down vote up
public String learn() {
	/**
	 * Simple explanation of these steps:
	 * 
	 * 1) If it is currently learning, change the inputs to either true or false.
	 * 
	 * 2) Let the NN tick and think. This will return the outputs from the OutpuitNeurons
	 * 
	 * 3) If it is not learning, just return the answer.
	 * 
	 * 4) Else, do the logic and see if the answer it gave (thought[0]) was correct.
	 * 
	 * 5) If it was not correct, use the DeepReinforcementUtil to improve it.
	 * 
	 * 6) After inprovement, return a message with if it was correct, the accuracy, the inputs, and what it thought was the output,
	 */
	binary.changeValueAt(0, 0,
			ThreadLocalRandom.current().nextBoolean());
	binary.changeValueAt(0, 1,
			ThreadLocalRandom.current().nextBoolean());
	boolean[] thought = tickAndThink();
	boolean logic = (binary.getBooleanAt(0, 0) && binary.getBooleanAt(0, 1));
	boolean wasCorrect = (logic == thought[0]);
	this.getAccuracy().addEntry(wasCorrect);

	// IMPROVE IT
	HashMap<Neuron, Double> map = new HashMap<>();
	for (int i = 0; i < thought.length; i++)
		map.put(ai.getNeuronFromId(i), logic ? 1.0 : -1.0);
	if (!wasCorrect)
		DeepReinforcementUtil.instantaneousReinforce(this, map,1);

	return (wasCorrect ? ChatColor.GREEN : ChatColor.RED) + "acc "
			+ getAccuracy().getAccuracyAsInt() + "|"
			+ binary.getBooleanAt(0, 0) + " + " + binary.getBooleanAt(0, 1)
			+ " ~~ " + thought[0];
	
}
 
Example 20
Source Project: pinpoint   Source File: AgentWarningStatServiceTest.java    License: Apache License 2.0 5 votes vote down vote up
private List<DeadlockThreadCountBo> createMockData(int mockSize, long interval) {
    long timestamp = ThreadLocalRandom.current().nextLong(START_TIME, CURRENT_TIME);

    List<DeadlockThreadCountBo> deadlockThreadCountBoList = new ArrayList<>(mockSize);
    for (int i = 0; i < mockSize; i++) {
        DeadlockThreadCountBo deadlockThreadCountBo = new DeadlockThreadCountBo();
        deadlockThreadCountBo.setAgentId("pinpoint");
        deadlockThreadCountBo.setStartTimestamp(START_TIME);
        deadlockThreadCountBo.setTimestamp(timestamp + (i * interval));

        deadlockThreadCountBoList.add(deadlockThreadCountBo);
    }

    return deadlockThreadCountBoList;
}
 
Example 21
/**
 * A sequential unsized stream of doubles generates at least 100 values
 */
public void testUnsizedDoublesCountSeq() {
    LongAdder counter = new LongAdder();
    ThreadLocalRandom r = ThreadLocalRandom.current();
    long size = 100;
    r.doubles().limit(size).forEach(x -> {
        counter.increment();
    });
    assertEquals(counter.sum(), size);
}
 
Example 22
/**
 * Repeated calls to nextFloat produce at least two distinct results
 */
public void testNextFloat() {
    float f = ThreadLocalRandom.current().nextFloat();
    int i = 0;
    while (i < NCALLS && ThreadLocalRandom.current().nextFloat() == f)
        ++i;
    assertTrue(i < NCALLS);
}
 
Example 23
Source Project: hottub   Source File: BigInteger.java    License: 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 24
Source Project: Path-of-Leveling   Source File: POELevelFx.java    License: MIT License 5 votes vote down vote up
private static int sign_jsons(HashSet<Integer> unique_ids){
    if(unique_ids == null) unique_ids = new HashSet<>();
    int ran;
    do{
        ran = ThreadLocalRandom.current().nextInt(1,999999);
    }while(unique_ids.contains(ran));
    unique_ids.add(ran);
    return ran;
}
 
Example 25
Source Project: hbase   Source File: TestClientTimeouts.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void callMethod(MethodDescriptor md, RpcController controller, Message param,
    Message returnType, RpcCallback<Message> done) {
  invokations.getAndIncrement();
  if (ThreadLocalRandom.current().nextFloat() < CHANCE_OF_TIMEOUT) {
    // throw a ServiceException, because that is the only exception type that
    // {@link ProtobufRpcEngine} throws. If this RpcEngine is used with a different
    // "actual" type, this may not properly mimic the underlying RpcEngine.
    ((HBaseRpcController) controller).setFailed(new SocketTimeoutException("fake timeout"));
    done.run(null);
    return;
  }
  super.callMethod(md, controller, param, returnType, done);
}
 
Example 26
Source Project: drift   Source File: TestDriftServer.java    License: Apache License 2.0 5 votes vote down vote up
private static void assertNormalInvocation(
        ResultsSupplier resultsSupplier,
        TestingServerTransport serverTransport,
        TestingInvocationTarget invocationTarget,
        TestingMethodInvocationStatsFactory statsFactory,
        Optional<String> qualifier)
        throws ExecutionException
{
    TestingMethodInvocationStat testStat = statsFactory.getStat("serverService", qualifier, "test");
    testStat.clear();
    int invocationId = ThreadLocalRandom.current().nextInt();
    String expectedResult = "result " + invocationId;
    resultsSupplier.setSuccessResult(expectedResult);
    ListenableFuture<Object> result = serverTransport.invoke("test", ImmutableMap.of(), ImmutableMap.of((short) 1, invocationId, (short) 2, "normal"));
    assertTrue(result.isDone());
    assertEquals(getDone(result), expectedResult);
    invocationTarget.assertInvocation("test", invocationId, "normal");
    testStat.assertSuccess();

    TestingMethodInvocationStat testAsyncStat = statsFactory.getStat("serverService", qualifier, "testAsync");
    testAsyncStat.clear();
    invocationId = ThreadLocalRandom.current().nextInt();
    expectedResult = "async " + expectedResult;
    resultsSupplier.setSuccessResult(expectedResult);
    ListenableFuture<Object> asyncResult = serverTransport.invoke("testAsync", ImmutableMap.of(), ImmutableMap.of((short) 1, invocationId, (short) 2, "async"));
    assertTrue(asyncResult.isDone());
    assertEquals(getDone(asyncResult), expectedResult);
    invocationTarget.assertInvocation("testAsync", invocationId, "async");
    testAsyncStat.assertSuccess();
}
 
Example 27
Source Project: hottub   Source File: ThreadLocalRandomTest.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * nextLong(bound) returns 0 <= value < bound; repeated calls produce at
 * least two distinct results
 */
public void testNextLongBounded() {
    for (long bound = 2; bound < MAX_LONG_BOUND; bound += 15485863) {
        long f = ThreadLocalRandom.current().nextLong(bound);
        assertTrue(0 <= f && f < bound);
        int i = 0;
        long j;
        while (i < NCALLS &&
               (j = ThreadLocalRandom.current().nextLong(bound)) == f) {
            assertTrue(0 <= j && j < bound);
            ++i;
        }
        assertTrue(i < NCALLS);
    }
}
 
Example 28
Source Project: j2objc   Source File: ThreadLocalRandom8Test.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * A parallel unsized stream of ints generates at least 100 values
 */
public void testUnsizedIntsCount() {
    LongAdder counter = new LongAdder();
    ThreadLocalRandom r = ThreadLocalRandom.current();
    long size = 100;
    r.ints().limit(size).parallel().forEach(x -> counter.increment());
    assertEquals(size, counter.sum());
}
 
Example 29
Source Project: DeskChan   Source File: ImageSetSkin.java    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
protected Sprite getFromFiles(List<File> list){
	int i = ThreadLocalRandom.current().nextInt(0, list.size());
	File image = list.get(i);
	try {
		return Sprite.getSpriteFromFile(image);
	} catch (Exception e){
		Main.log(e);
		return null;
	}
}
 
Example 30
public void run() {
    try {
        ThreadLocalRandom rand = ThreadLocalRandom.current();
        Thread.sleep(rand.nextInt(10) + 10);
    } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
    }
    int actual = stripeSequence.getAndIncrement();
    if (actual != expected) {
        outOfSequence = true;
    }
    //System.out.printf("Execute strip %h %d %d%n", stripe, actual, expected);
    assertEquals("out of sequence", actual, expected);
}