Java 类java.util.concurrent.ThreadLocalRandom 实例源码

项目:dremio-oss    文件:RoundRobinOperator.java   
public RoundRobinOperator(TunnelProvider tunnelProvider, OperatorContext context, RoundRobinSender config) throws OutOfMemoryException {
  super(config);
  this.config = config;
  this.allocator = context.getAllocator();
  this.handle = context.getFragmentHandle();
  this.stats = context.getStats();

  List<MinorFragmentEndpoint> destinations = config.getDestinations();
  final ArrayListMultimap<NodeEndpoint, Integer> dests = ArrayListMultimap.create();
  for(MinorFragmentEndpoint destination : destinations) {
    dests.put(destination.getEndpoint(), destination.getId());
  }

  this.tunnels = new ArrayList<>();
  this.minorFragments = new ArrayList<>();
  for(final NodeEndpoint ep : dests.keySet()){
    List<Integer> minorsList= dests.get(ep);
    minorFragments.add(minorsList);
    tunnels.add(tunnelProvider.getExecTunnel(ep));
  }

  int destCount = dests.keySet().size();
  this.currentTunnelsIndex = ThreadLocalRandom.current().nextInt(destCount);
  this.currentMinorFragmentsIndex = ThreadLocalRandom.current().nextInt(minorFragments.get(currentTunnelsIndex).size());
}
项目:openjdk-jdk10    文件:ThreadLocalRandomTest.java   
/**
 * nextDouble(least, bound) returns least <= value < bound;
 * repeated calls produce at least two distinct results
 */
public void testNextDoubleBounded2() {
    for (double least = 0.0001; least < 1.0e20; least *= 8) {
        for (double bound = least * 1.001; bound < 1.0e20; bound *= 16) {
            double f = ThreadLocalRandom.current().nextDouble(least, bound);
            assertTrue(least <= f && f < bound);
            int i = 0;
            double j;
            while (i < NCALLS &&
                   (j = ThreadLocalRandom.current().nextDouble(least, bound)) == f) {
                assertTrue(least <= j && j < bound);
                ++i;
            }
            assertTrue(i < NCALLS);
        }
    }
}
项目:momo-2    文件:Util.java   
/**
 * Get an image link from an imgur album
 * @param albumId Album ID
 * @return Link to an image
 * @throws NoAPIKeyException No imgur key setup
 */
public static String getRandomImageLinkForImgurId(String albumId) throws NoAPIKeyException {
    try {
        URL url = new URL(String.format("https://api.imgur.com/3/album/%s/images", albumId));
        HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
        urlConnection.setRequestProperty("Authorization", "Client-ID "
                + Bot.getInstance().getApiKeys().get("imgur"));
        urlConnection.connect();
        StringBuilder stb = new StringBuilder();
        // Get the response
        BufferedReader rd = new BufferedReader(
                new InputStreamReader(urlConnection.getInputStream()));
        String line;
        while ((line = rd.readLine()) != null) {
            stb.append(line).append("\n");
        }
        JsonArray ja = Json.parse(stb.toString()).asObject().get("data").asArray();
        int randomInt = ThreadLocalRandom.current().nextInt(0, ja.size());
        String imgurLink = ja.get(randomInt).asObject().get("link").asString();

        return imgurLink;
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}
项目:incubator-ratis    文件:TestRaftStorage.java   
@Test
public void testSnapshotFileName() throws Exception {
  final long term = ThreadLocalRandom.current().nextLong(Long.MAX_VALUE);
  final long index = ThreadLocalRandom.current().nextLong(Long.MAX_VALUE);
  final String name = SimpleStateMachineStorage.getSnapshotFileName(term, index);
  System.out.println("name = " + name);
  final File file = new File(storageDir, name);
  final TermIndex ti = SimpleStateMachineStorage.getTermIndexFromSnapshotFile(file);
  System.out.println("file = " + file);
  Assert.assertEquals(term, ti.getTerm());
  Assert.assertEquals(index, ti.getIndex());
  System.out.println("ti = " + ti);

  final File foo = new File(storageDir, "foo");
  try {
    SimpleStateMachineStorage.getTermIndexFromSnapshotFile(foo);
    Assert.fail();
  } catch(IllegalArgumentException iae) {
    System.out.println("Good " + iae);
  }
}
项目:jdk8u-jdk    文件:ThreadLocalRandomTest.java   
/**
 * A parallel sized stream of doubles generates the given number of values
 */
public void testDoublesCount() {
    LongAdder counter = new LongAdder();
    ThreadLocalRandom r = ThreadLocalRandom.current();
    long size = 0;
    for (int reps = 0; reps < REPS; ++reps) {
        counter.reset();
        r.doubles(size).parallel().forEach(x -> {
            counter.increment();
        });
        assertEquals(counter.sum(), size);
        size += 524959;
    }
}
项目:jdk8u-jdk    文件:ThreadLocalRandomTest.java   
/**
 * nextLong(least, bound) returns least <= value < bound; repeated calls
 * produce at least two distinct results
 */
public void testNextLongBounded2() {
    for (long least = -86028121; least < MAX_LONG_BOUND; least += 982451653L) {
        for (long bound = least + 2; bound > least && bound < MAX_LONG_BOUND; bound += Math.abs(bound * 7919)) {
            long f = ThreadLocalRandom.current().nextLong(least, bound);
            assertTrue(least <= f && f < bound);
            int i = 0;
            long j;
            while (i < NCALLS &&
                   (j = ThreadLocalRandom.current().nextLong(least, bound)) == f) {
                assertTrue(least <= j && j < bound);
                ++i;
            }
            assertTrue(i < NCALLS);
        }
    }
}
项目:Java-9-with-JShell    文件:example10_01.java   
public void declareNewPartyLeader() throws InsufficientMembersException {
    if (members.size() == 1) {
        throw new InsufficientMembersException(members.size());
    }
    T newPartyLeader = partyLeader;
    while (newPartyLeader.equals(partyLeader)) {
        int pseudoRandomIndex = 
            ThreadLocalRandom.current().nextInt(
                0,
                members.size());
        newPartyLeader = members.get(pseudoRandomIndex);
    }
    partyLeader.speak(
        String.format("%s is our new party leader.", 
            newPartyLeader.getName()));
    newPartyLeader.danceWith(partyLeader);
    if (newPartyLeader.compareTo(partyLeader) < 0) {
        // The new party leader is younger
        newPartyLeader.danceAlone();
    }
    partyLeader = newPartyLeader;
}
项目:openjdk-jdk10    文件:ThreadLocalRandomTest.java   
/**
 * nextLong(least, bound) returns least <= value < bound;
 * repeated calls produce at least two distinct results
 */
public void testNextLongBounded2() {
    for (long least = -86028121; least < MAX_LONG_BOUND; least += 982451653L) {
        for (long bound = least + 2; bound > least && bound < MAX_LONG_BOUND; bound += Math.abs(bound * 7919)) {
            long f = ThreadLocalRandom.current().nextLong(least, bound);
            assertTrue(least <= f && f < bound);
            int i = 0;
            long j;
            while (i < NCALLS &&
                   (j = ThreadLocalRandom.current().nextLong(least, bound)) == f) {
                assertTrue(least <= j && j < bound);
                ++i;
            }
            assertTrue(i < NCALLS);
        }
    }
}
项目:NeuralNetworkAPI    文件:QuickBlackJackHandler.java   
public void newDeck(){
    currentIndex=0;
    List<Integer> usedSlots = new ArrayList<>();
    List<Card> originDeck = Card.newOrderedDeck();
    cardsInDeck = new Card[52];
    Random r = ThreadLocalRandom.current();

    //Shuffle
    for(int i = 0; i < originDeck.size();i++){
        int newGoodIndex = r.nextInt(cardsInDeck.length);
        while(true){
        if(usedSlots.contains(newGoodIndex)){
            newGoodIndex=(newGoodIndex+1)%originDeck.size();
        }else{
            usedSlots.add(newGoodIndex);
            cardsInDeck[newGoodIndex] = originDeck.get(i);
            break;
        }
        }
    }
}
项目:JRediClients    文件:RedissonMapCacheTest.java   
@Test
public void testIteratorRandomRemoveHighVolume() throws InterruptedException {
    RMapCache<Integer, Integer> map = redisson.getMapCache("simpleMap");
    for (int i = 0; i < 10000; i++) {
        map.put(i, i*10);
    }

    int cnt = 0;
    int removed = 0;
    Iterator<Entry<Integer, Integer>> iterator = map.entrySet().iterator();
    while (iterator.hasNext()) {
        Entry<Integer, Integer> entry = iterator.next();
        if (ThreadLocalRandom.current().nextBoolean()) {
            iterator.remove();
            removed++;
        }
        cnt++;
    }
    Assert.assertEquals(10000, cnt);
    assertThat(map.size()).isEqualTo(cnt - removed);
}
项目:Java-9-with-JShell    文件:example10_03.java   
public void declareNewPartyLeader() throws InsufficientMembersException {
    if (members.size() == 1) {
        throw new InsufficientMembersException(members.size());
    }
    T newPartyLeader = partyLeader;
    while (newPartyLeader.equals(partyLeader)) {
        int pseudoRandomIndex = 
            ThreadLocalRandom.current().nextInt(
                0,
                members.size());
        newPartyLeader = members.get(pseudoRandomIndex);
    }
    partyLeader.speak(
        String.format("%s is our new party leader.", 
            newPartyLeader.getName()));
    newPartyLeader.danceWith(partyLeader);
    if (newPartyLeader.compareTo(partyLeader) < 0) {
        // The new party leader is younger
        newPartyLeader.danceAlone();
    }
    partyLeader = newPartyLeader;
}
项目:JInsight    文件:JedisInstrumentationTest.java   
@Test
public void testSortedSetAddRemove() throws Exception {
  int rnd = ThreadLocalRandom.current().nextInt(0, presetElements.size());
  String key = presetElementKeys.get(rnd);
  String value = String.valueOf(presetElements.get(key));

  Snapshot snapshot = tracker.snapshot();
  snapshot.increment("zadd");
  Long added = jedis.zadd(key, 1, value);
  assertEquals(1, (long) added);

  snapshot.increment("zrem");
  Long removed = jedis.zrem(key, value);
  assertEquals(1, (long) removed);
  snapshot.validate();
}
项目:FuzzDroid    文件:IncomingCallEvent.java   
@Override
public Object onEventReceived(IDevice device) {
    String senderNumber = "";
    for(int i = 0; i < 8; i++)
        senderNumber += ThreadLocalRandom.current().nextInt(0, 9 + 1);

    EmulatorConsole emulatorConsole = EmulatorConsole.getConsole(device);
    LoggerHelper.logEvent(MyLevel.ADB_EVENT, adbEventFormat(toString(), String.format("incomingCall(%s)", senderNumber)));
    //call a random number
    emulatorConsole.call(senderNumber);
    //let it ring for 3 seconds
    try {
        Thread.sleep(3000);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    //cancel call
    emulatorConsole.cancelCall(senderNumber);
    return null;
}
项目:ProjectAltaria    文件:RandomNumberCommand.java   
private void handleCoinToss(@NotNull MessageReceivedEvent event, @NotNull List<String> args) {
    int iterations = 1;
    if (args.size() > 1 && INT_PATTERN.matcher(args.get(1)).find()) {
        iterations = Math.min(12, Integer.parseUnsignedInt(args.get(1)));
    }
    int sIterations = 0;
    ThreadLocalRandom random = ThreadLocalRandom.current();
    EmbedBuilder builder = MessageUtils.getEmbedBuilder(event.getMessage().getAuthor());
    int heads = 0;
    int tails = 0;
    while (sIterations++ != iterations) {
        boolean res = random.nextBoolean();

        if (res) heads++;
        else tails++;

        builder.appendField("Round " + (sIterations), res ? "Head" : "Tail", true);
    }
    builder.withTitle("Tossed " + (sIterations - 1) + (sIterations == 1 ? " coin" : " coins"));
    builder.withDescription("Heads: " + heads + ". Tails: " + tails);

    sendThenDelete(MessageUtils.getMessageBuilder(event.getMessage())
            .withEmbed(builder.build()));
    delete(event.getMessage());
}
项目:shared-ledger-simulator    文件:SerializationTester.java   
public static void main(String[] args){
    byte[] sourceAddress = new byte[20];        
    //Random random = new Random(); 
    //random.nextBytes(sourceAddress);
    ThreadLocalRandom.current().nextBytes(sourceAddress);

    byte[] publicKey = new byte[120];
    ThreadLocalRandom.current().nextBytes(publicKey);

    UnsignedTransaction unsignedTransaction = new UnsignedTransaction(sourceAddress, 
            RandomTransactionProvider.createAddressesAndAmounts(2), publicKey);
    log.info("Unsigned transaction: " + unsignedTransaction);
    byte[] bytes = Serializer.serialize(unsignedTransaction);
    log.info("Serialization bytes: " + Arrays.toString(bytes));
    log.info("Serialization bytes length: " + bytes.length);

    UnsignedTransaction deserializedUT = Deserializer.createObject(bytes, UnsignedTransaction.class);
    log.info("\nDeserialized unsigned transaction: " + deserializedUT);
    log.info("Are the two unsigned transactions equal?: " + unsignedTransaction.equals(deserializedUT));        
}
项目:Nukkit-Java9    文件:BlockOreCoal.java   
@Override
public Item[] getDrops(Item item) {
    if (item.isPickaxe() && item.getTier() >= ItemTool.TIER_WOODEN) {
        int count = 1;
        Enchantment fortune = item.getEnchantment(Enchantment.ID_FORTUNE_DIGGING);
        if (fortune != null && fortune.getLevel() >= 1) {
            int i = ThreadLocalRandom.current().nextInt(fortune.getLevel() + 2) - 1;

            if (i < 0) {
                i = 0;
            }

            count = i + 1;
        }

        return new Item[]{
                new ItemCoal(0, count)
        };
    } else {
        return new Item[0];
    }
}
项目:Nukkit-Java9    文件:BlockOreDiamond.java   
@Override
public Item[] getDrops(Item item) {
    if (item.isPickaxe() && item.getTier() >= ItemTool.TIER_IRON) {
        int count = 1;
        Enchantment fortune = item.getEnchantment(Enchantment.ID_FORTUNE_DIGGING);
        if (fortune != null && fortune.getLevel() >= 1) {
            int i = ThreadLocalRandom.current().nextInt(fortune.getLevel() + 2) - 1;

            if (i < 0) {
                i = 0;
            }

            count = i + 1;
        }

        return new Item[]{
                new ItemDiamond(0, count)
        };
    } else {
        return new Item[0];
    }
}
项目:openjdk-jdk10    文件:ThreadLocalRandomTest.java   
/**
 * nextDouble(non-positive) throws IllegalArgumentException
 */
public void testNextDoubleBoundNonPositive() {
    ThreadLocalRandom rnd = ThreadLocalRandom.current();
    double[] badBounds = {
        0.0d,
        -17.0d,
        -Double.MIN_VALUE,
        Double.NEGATIVE_INFINITY,
        Double.NaN,
    };
    for (double bound : badBounds) {
        try {
            rnd.nextDouble(bound);
            shouldThrow();
        } catch (IllegalArgumentException success) {}
    }
}
项目:JInsight    文件:JedisTransactionInstrumentationTest.java   
@Test
public void testDiscard() throws Exception {
  int rnd = ThreadLocalRandom.current().nextInt(0, presetElements.size());
  String key = presetElementKeys.get(rnd);
  String value = String.valueOf(presetElements.get(key));

  Transaction transaction = jedis.multi();

  Snapshot snapshot = commandTracker.snapshot();
  Snapshot discardSnapshot = discardTracker.snapshot();
  Snapshot txsnapshot = execTracker.snapshot();
  discardSnapshot.increment();
  Response<Long> added = transaction.sadd(key, value);
  transaction.discard();
  assertNull(jedis.get(key));
  txsnapshot.validate();
  snapshot.validate();
  discardSnapshot.validate();
}
项目:yet-another-try    文件:AsyncRetryExecutorBuilderTest.java   
@Test
public void it_should_set_max_attempts() {
  assertThat(createBuilder())
      .assertIsSet(
          builder -> {
            int maxAttempts = ThreadLocalRandom.current()
                .nextInt(10);
            builder.maxAttempts(maxAttempts);
            return maxAttempts;
          },
          AsyncRetryExecutorBuilder::maxAttempts
      )
      .assertIsSet(
          builder -> { builder.retryOnce(); return 2; },
          AsyncRetryExecutorBuilder::maxAttempts
      )
      .assertIsSet(
          builder -> { builder.doNotRetry(); return 1; },
          AsyncRetryExecutorBuilder::maxAttempts
      )
      .assertBuilt();
}
项目:AlphaLibary    文件:AnnotatedRandom.java   
final AnnotatedRandom apply() {
    try {
        if (strIntDouble instanceof String)
            Accessor.access(randomField).set(randomClazz, Util.generateRandomString(length));
        else if (strIntDouble instanceof Integer)
            Accessor.access(randomField).set(randomClazz, ThreadLocalRandom.current().nextInt(length));
        else if (strIntDouble instanceof Double)
            Accessor.access(randomField).set(randomClazz, ThreadLocalRandom.current().nextDouble(length));
        else if (strIntDouble instanceof Boolean)
            Accessor.access(randomField).set(randomClazz, ThreadLocalRandom.current().nextBoolean());
        else if (strIntDouble instanceof UUID)
            Accessor.access(randomField).set(randomClazz, UUID.randomUUID());
    } catch (ReflectiveOperationException e) {
        e.printStackTrace();
    }

    return this;
}
项目:shared-ledger-simulator    文件:RewardAndFeeOutputsTest.java   
@Test
public void testAdd1(){
    byte[] minerAddress = new byte[20];        
    ThreadLocalRandom.current().nextBytes(minerAddress);

    AddressAndAmount rewardOutput = new AddressAndAmount(minerAddress, 50);
    AddressAndAmount feeOutput = new AddressAndAmount(minerAddress, 22);        

    List<AddressAndAmount> outputList =  new ArrayList<AddressAndAmount>(2);
    outputList.add(rewardOutput);
    outputList.add(feeOutput);
    UnsignedTransaction unsignedTransaction = new UnsignedTransaction(null, outputList, null);
    Transaction transaction = new Transaction(unsignedTransaction, null);

    RewardAndFeeOutputs rewardAndFeeOutputs = new RewardAndFeeOutputs();
    boolean correct = rewardAndFeeOutputs.add(transaction, minerAddress, 50);
    Assert.assertTrue(correct);
    Assert.assertEquals(22, rewardAndFeeOutputs.getFee());
}
项目:openjdk-jdk10    文件:ArrayBlockingQueueTest.java   
/**
 * Returns a new queue of given size containing consecutive
 * Integers 0 ... n - 1, with given capacity range and fairness.
 */
static ArrayBlockingQueue<Integer> populatedQueue(
    int size, int minCapacity, int maxCapacity, boolean fair) {
    ThreadLocalRandom rnd = ThreadLocalRandom.current();
    int capacity = rnd.nextInt(minCapacity, maxCapacity + 1);
    ArrayBlockingQueue<Integer> q = new ArrayBlockingQueue<>(capacity);
    assertTrue(q.isEmpty());
    // shuffle circular array elements so they wrap
    {
        int n = rnd.nextInt(capacity);
        for (int i = 0; i < n; i++) q.add(42);
        for (int i = 0; i < n; i++) q.remove();
    }
    for (int i = 0; i < size; i++)
        assertTrue(q.offer((Integer) i));
    assertEquals(size == 0, q.isEmpty());
    assertEquals(capacity - size, q.remainingCapacity());
    assertEquals(size, q.size());
    if (size > 0)
        assertEquals((Integer) 0, q.peek());
    return q;
}
项目:incubator-ratis    文件:CollectionUtils.java   
/**
 *  @return a randomly picked element which is not the given element.
 */
static <T> T random(final T given, Iterable<T> iteration) {
  Objects.requireNonNull(given, "given == null");
  Objects.requireNonNull(iteration, "iteration == null");
  Preconditions.assertTrue(iteration.iterator().hasNext(), "iteration is empty");

  final List<T> list = StreamSupport.stream(iteration.spliterator(), false)
      .filter(e -> !given.equals(e))
      .collect(Collectors.toList());
  final int size = list.size();
  return size == 0? null: list.get(ThreadLocalRandom.current().nextInt(size));
}
项目:popular-movie-store    文件:MovieDBHelper.java   
/**
 * This method queries the external API and caches the movies, for the demo purpose we just query only first page
 *
 * @return - the status code of the invocation
 */
protected int queryAndCache() {

    if (this.moviesCache.isEmpty()) {

        log.info("No movies exist in cache, loading cache ..");

        UriComponentsBuilder moviesUri = UriComponentsBuilder
            .fromUriString(movieStoreProps.getApiEndpointUrl() + "/movie/popular")
            .queryParam("api_key", movieStoreProps.getApiKey());

        final URI requestUri = moviesUri.build().toUri();

        log.info("Request URI:{}", requestUri);

        ResponseEntity<String> response = restTemplate.getForEntity(requestUri, String.class);

        log.info("Response Status:{}", response.getStatusCode());

        Map<String, Movie> movieMap = new HashMap<>();

        if (200 == response.getStatusCode().value()) {
            String jsonBody = response.getBody();
            ObjectMapper objectMapper = new ObjectMapper();
            try {
                JsonNode root = objectMapper.readTree(jsonBody);
                JsonNode results = root.path("results");
                results.elements().forEachRemaining(movieNode -> {
                    String id = movieNode.get("id").asText();
                    Movie movie = Movie.builder()
                        .id(id)
                        .overview(movieNode.get("overview").asText())
                        .popularity(movieNode.get("popularity").floatValue())
                        .posterPath("http://image.tmdb.org/t/p/w92" + movieNode.get("poster_path").asText())
                        .logoPath("http://image.tmdb.org/t/p/w45" + movieNode.get("poster_path").asText())
                        .title(movieNode.get("title").asText())
                        .price(ThreadLocalRandom.current().nextDouble(1.0, 10.0))
                        .build();
                    movieMap.put(id, movie);
                });
            } catch (IOException e) {
                log.error("Error reading response:", e);
            }

            log.debug("Got {} movies", movieMap);
            moviesCache.putAll(movieMap);
        }
        return response.getStatusCode().value();
    } else {
        log.info("Cache already loaded with movies ... will use cache");
        return 200;
    }
}
项目:grpc-java-contrib    文件:GrpcServerHostTest.java   
@Test
public void startThrowsForBadServices() {
    final String badService1 = UUID.randomUUID().toString();
    final String badService2 = UUID.randomUUID().toString();
    final String goodService = UUID.randomUUID().toString();
    final int port = ThreadLocalRandom.current().nextInt(1000, 10000);
    final long shutdownWaitTimeInMillis = ThreadLocalRandom.current().nextLong(1000, 10000);

    final ApplicationContext applicationContext = mock(ApplicationContext.class);

    final Map<String, Object> services = ImmutableMap.of(
            badService1, new Object(),
            badService2, new Object(),
            goodService, new GreeterGrpc.GreeterImplBase() { });

    when(applicationContext.getBeansWithAnnotation(eq(GrpcService.class))).thenReturn(services);

    GrpcServerHost runner = new GrpcServerHost(port, shutdownWaitTimeInMillis);
    runner.setApplicationContext(applicationContext);

    assertThatThrownBy(runner::start)
            .isInstanceOf(IllegalStateException.class)
            .doesNotHave(new Condition<Throwable>(
                    t -> t.getMessage().contains(goodService),
                    "Error should not include good service."))
            .hasMessageContaining(badService1)
            .hasMessageContaining(badService2);
}
项目:schematic    文件:RandomUtil.java   
/**
 * Generates a random string of a length with a range, inclusive on either end.
 * @param min   min length
 * @param max   max length
 * @return a random string whose length is with the provided boundaries (inclusive)
 */
public static String nextString(Integer min, Integer max) {
    int length = stringLength(adjustStringLength(min), adjustStringLength(max));

    StringBuilder sb = new StringBuilder(length);
    Random random = ThreadLocalRandom.current();
    for (int i = 0; i < length; i++) {
        sb.append(RAND_CHARS.charAt(random.nextInt(RAND_CHARS.length())));
    }
    return sb.toString();
}
项目:HCFCore    文件:ArmorFixListener.java   
@EventHandler
public void onItemDamage(PlayerItemDamageEvent event)
{
  ItemStack stack = event.getItem();
  if ((stack != null) && (ALLOWED.contains(stack.getType())) && 
    (ThreadLocalRandom.current().nextInt(3) != 0)) {
    event.setCancelled(true);
  }
}
项目:shared-ledger-simulator    文件:BlockTreeConstructorTester.java   
public static Block provideRandomGenesisBlock(){
    byte[] minerAddress = new byte[20];        
    ThreadLocalRandom.current().nextBytes(minerAddress);
    List<Transaction> transactions = RandomTransactionsProvider.provide();
    Block block = new Block(transactions, null, minerAddress, 0);
    return block;
}
项目:ditb    文件:MultiThreadedClientExample.java   
@Override
public Boolean call() throws Exception {
  try (Table t = connection.getTable(tableName)) {

    byte[] value = Bytes.toBytes(Double.toString(ThreadLocalRandom.current().nextDouble()));
    byte[] rk = Bytes.toBytes(ThreadLocalRandom.current().nextLong());
    Put p = new Put(rk);
    p.addImmutable(FAMILY, QUAL, value);
    t.put(p);
  }
  return true;
}
项目:Prospecting    文件:ProspectingSavedData.java   
private int getNuggetAmount(float amt) {
    int divisor = Prospecting.config.ore_per_nugget + (ThreadLocalRandom.current().nextInt(0, (Prospecting.config.ore_per_nugget_deviation * 2) + 1)) - Prospecting.config.ore_per_nugget_deviation;
    int r = (int) (amt / divisor);
    if (r > Prospecting.config.max_nuggets) {
        return Prospecting.config.max_nuggets;
    } else if (r < 0) {
        return 0;
    }
    return r;
}
项目:dremio-oss    文件:SpoolingRawBatchBuffer.java   
public void writeToStream(FSDataOutputStream stream) throws IOException {
  Stopwatch watch = Stopwatch.createStarted();
  ByteBuf buf = null;
  try {
    check = ThreadLocalRandom.current().nextLong();
    start = stream.getPos();
    logger.debug("Writing check value {} at position {}", check, start);
    stream.writeLong(check);
    batch.getHeader().writeDelimitedTo(stream);
    buf = batch.getBody();
    if (buf != null) {
      bodyLength = buf.capacity();
    } else {
      bodyLength = 0;
    }
    if (bodyLength > 0) {
      buf.getBytes(0, stream, bodyLength);
    }
    stream.hsync();
    FileStatus status = spillFile.getFileStatus();
    long len = status.getLen();
    logger.debug("After spooling batch, stream at position {}. File length {}", stream.getPos(), len);
    long t = watch.elapsed(TimeUnit.MICROSECONDS);
    logger.debug("Took {} us to spool {} to disk. Rate {} mb/s", t, bodyLength, bodyLength / t);
  } finally {
    // even if the try block throws an exception we still want to send an ACK and release the lock
    // the caller will add the exception to deferred attribute and it will be thrown when the poll() method is called
    try {
      batch.sendOk(); // this can also throw an exception
    } finally {
      state = BatchState.SPILLED;
      batch = null;
      if (buf != null) {
        buf.release();
      }
    }
  }
}
项目:proteus-consumer-couchbase    文件:ProteusSerializatorTest.java   
@Test
public void testHSMSerializationAndDeserialization() {
    int coilId = ThreadLocalRandom.current().nextInt(3000, 8000);
    HSMMeasurement record = new HSMMeasurement(coilId);

    Map<String, Object> map = createFakeHSMValues();
    record.setVariables(map);

    byte[] bytes = this.kryo.serialize("proteus-hsm", record);

    HSMMeasurement deserialized = (HSMMeasurement) this.kryo.deserialize("proteus-hsm", bytes);

    assertEquals(record, deserialized);
}
项目:intellij-randomness    文件:IntegerInsertAction.java   
/**
 * Returns a random integer between the minimum and maximum value, inclusive.
 *
 * @return a random integer between the minimum and maximum value, inclusive
 */
@Override
public String generateString() {
    final long randomValue = ThreadLocalRandom.current()
            .nextLong(integerSettings.getMinValue(), integerSettings.getMaxValue() + 1);

    return convertToString(randomValue);
}
项目:openjdk-jdk10    文件:ThreadLocalRandomTest.java   
/**
 * nextLong(least >= bound) throws IllegalArgumentException
 */
public void testNextLongBadBounds() {
    long[][] badBoundss = {
        { 17L, 2L },
        { -42L, -42L },
        { Long.MAX_VALUE, Long.MIN_VALUE },
    };
    ThreadLocalRandom rnd = ThreadLocalRandom.current();
    for (long[] badBounds : badBoundss) {
        try {
            rnd.nextLong(badBounds[0], badBounds[1]);
            shouldThrow();
        } catch (IllegalArgumentException success) {}
    }
}
项目:grpc-java-contrib    文件:ProtoTypeUtilsTest.java   
@Test
public void classWithEnclosingClassAndJavaPackage() {
    final String className = randomAlphabetic(ThreadLocalRandom.current().nextInt(5, 10));
    final String enclosingClassName = randomAlphabetic(ThreadLocalRandom.current().nextInt(5, 10));
    final String javaPackage = randomAlphabetic(ThreadLocalRandom.current().nextInt(5, 10));

    assertThat(ProtoTypeMap.toJavaTypeName(className, enclosingClassName, javaPackage))
            .isEqualTo(javaPackage + "." + enclosingClassName + "." + className);
}
项目:jspare-vertx-ms-blueprint    文件:TidGenerator.java   
public String generate() {

        StringBuilder tid = new StringBuilder();
        tid.append(LocalDateTime.now().format(dtf));
        tid.append(StringUtils.leftPad(String.valueOf(ThreadLocalRandom.current().nextLong(MIN, MAX)), 6, "0"));
        tid.append(calculateVerifyDigit(tid.toString()));
        return tid.toString();
    }
项目:simdbenchmarks    文件:HashSetContainsBenchmark.java   
private static Builder newBuilderInstance() {
    ThreadLocalRandom random = ThreadLocalRandom.current();
    return new Builder(UUID.randomUUID().toString(),
            random.nextInt(),
            UUID.randomUUID().toString(),
            Instant.ofEpochMilli(random.nextLong(0, Instant.now().toEpochMilli())));
}
项目:app-ms    文件:RequestIDProvider.java   
/**
 * Provides a new request ID, adds it to the context along with the response
 * headers and sets the MDC as well.
 *
 * @param context
 *            routing context
 * @return random string.
 */
public String newRequestID(final RoutingContext context) {

    final Random random = ThreadLocalRandom.current();
    final char[] buf = new char[LENGTH];
    for (int i = 0; i < LENGTH; ++i) {
        buf[i] = ALLOWED_CHARACTERS[random.nextInt(ALLOWED_CHARACTERS.length)];
    }
    final String requestID = new String(buf);
    MDC.put(REQUEST_ID, requestID);
    context.data().put(REQUEST_ID, requestID);
    context.response().putHeader(REQUEST_ID, requestID);
    return requestID;
}
项目:openjdk-jdk10    文件:ArrayBlockingQueueTest.java   
/**
 * contains(x) reports true when elements added but not yet removed
 */
public void testContains() {
    int size = ThreadLocalRandom.current().nextInt(1, SIZE);
    ArrayBlockingQueue q = populatedQueue(size, size, 2 * size, false);
    assertFalse(q.contains(null));
    for (int i = 0; i < size; ++i) {
        assertTrue(q.contains(new Integer(i)));
        assertEquals(i, q.poll());
        assertFalse(q.contains(new Integer(i)));
    }
}