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

The following examples show how to use java.util.concurrent.ThreadLocalRandom#nextDouble() . 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: presto   File: BenchmarkEqualsOperator.java    License: Apache License 2.0 6 votes vote down vote up
@Setup
public void setup()
{
    List<Type> types = ImmutableList.copyOf(limit(cycle(BIGINT), FIELDS_COUNT));
    ThreadLocalRandom random = ThreadLocalRandom.current();
    PageBuilder pageBuilder = new PageBuilder(types);
    while (!pageBuilder.isFull()) {
        pageBuilder.declarePosition();
        for (int channel = 0; channel < FIELDS_COUNT; channel++) {
            BlockBuilder blockBuilder = pageBuilder.getBlockBuilder(channel);
            if (random.nextDouble() < NULLS_FRACTION) {
                blockBuilder.appendNull();
            }
            else {
                BIGINT.writeLong(blockBuilder, random.nextLong());
            }
        }
    }
    page = pageBuilder.build();
}
 
Example 2
/**
 * 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) {}
    }
}
 
Example 3
public void run(SourceContext<MonitoringEvent> sourceContext) throws Exception {
    while (running) {
        MonitoringEvent monitoringEvent;

        final ThreadLocalRandom random = ThreadLocalRandom.current();

        if (shard > 0) {
            int rackId = random.nextInt(shard) + offset;

            if (random.nextDouble() >= temperatureRatio) {
                double power = random.nextGaussian() * powerStd + powerMean;
                monitoringEvent = new PowerEvent(rackId, power);
            } else {
                double temperature = random.nextGaussian() * temperatureStd + temperatureMean;
                monitoringEvent = new TemperatureEvent(rackId, temperature);
            }


            sourceContext.collect(monitoringEvent);
        }

        Thread.sleep(pause);
    }
}
 
Example 4
Source Project: bboxdb   File: RTreeTestHelper.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Generate some random tuples
 * @return
 */
public static List<SpatialIndexEntry> generateRandomTupleList(final int dimensions, final int elements) {
	final List<SpatialIndexEntry> entryList = new ArrayList<>();
	final ThreadLocalRandom random = ThreadLocalRandom.current();
	
	for(int i = 0; i < elements; i++) {
		final double[] boundingBoxData = new double[dimensions * 2];
		
		for(int d = 0; d < dimensions; d++) {
			final double begin = random.nextDouble(-10000, 10000);
			final double extent = random.nextDouble(0, 50);
			boundingBoxData[2 * d] = begin;            // Start coordinate
			boundingBoxData[2 * d + 1] = begin+extent; // End coordinate
		}
		
		final Hyperrectangle bbox = new Hyperrectangle(boundingBoxData);
		final SpatialIndexEntry entry = new SpatialIndexEntry(bbox, i);
		entryList.add(entry);
	}

	return entryList;
}
 
Example 5
/** {@inheritDoc} */
@Override public boolean test(Map<Object, Object> ctx) throws Exception {
    ThreadLocalRandom rnd = ThreadLocalRandom.current();

    if (rnd.nextBoolean()) {
        double salary = rnd.nextDouble() * args.range() * 1000;

        double maxSalary = salary + 1000;

        Long res = (Long)cache().query(new SqlFieldsQuery("delete from Person where salary >= ? and salary <= ?")
            .setArgs(salary, maxSalary)).getAll().get(0).get(0);

        delItemsCnt.getAndAdd(res);

        delCnt.getAndIncrement();
    }
    else {
        int i = rnd.nextInt(args.range());

        cache.put(i, new Person(i, "firstName" + i, "lastName" + i, i * 1000));

        putCnt.getAndIncrement();
    }

    return true;
}
 
Example 6
Source Project: ignite   File: TrackingPageIOTest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * @param buf Buffer.
 * @param track Track.
 * @param basePageId Base page id.
 * @param maxPageId Max page id.
 * @param setIdx Set index.
 * @param backupId Backup id.
 * @param successfulBackupId Successful backup id.
 */
private void generateMarking(
    ByteBuffer buf,
    int track,
    long basePageId,
    long maxPageId,
    Set<Long> setIdx,
    int backupId, int successfulBackupId
) {
    ThreadLocalRandom rand = ThreadLocalRandom.current();

    for (long i = basePageId; i < basePageId + track; i++) {
        boolean changed = (i == basePageId || rand.nextDouble() < 0.1) && i < maxPageId;

        if (changed) {
            io.markChanged(buf, i, backupId, successfulBackupId, PAGE_SIZE);

            setIdx.add(i);
        }
    }
}
 
Example 7
Source Project: j2objc   File: ThreadLocalRandomTest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 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) {}
    }
}
 
Example 8
private AnimationPoint generateRandom(EntityPlayer player) {
    ThreadLocalRandom current = ThreadLocalRandom.current();
    double posX = player == null ? 0 : player.posX;
    double posY = player == null ? 0 : player.posY;
    double posZ = player == null ? 0 : player.posZ;
    double y = current.nextDouble(.5 + posY, posY + BOUNDS + (double) BOUNDS / 2D);
    return new AnimationPoint(current.nextDouble(-BOUNDS + posX, BOUNDS + posX), y,
        current.nextDouble(-BOUNDS + posZ, BOUNDS + posZ));
}
 
Example 9
Source Project: TabooLib   File: Effects.java    License: MIT License 5 votes vote down vote up
public static void buildLightning(Location start, Vector direction, int entries, int branches, double radius, double offset, double offsetRate, double length, double lengthRate, double branch, double branchRate, Consumer<Location> action) {
    ThreadLocalRandom random = ThreadLocalRandom.current();
    if (entries <= 0) {
        return;
    }
    boolean inRange = true;
    while (random.nextDouble() < branch || inRange) {
        Vector randomizer = new Vector(random.nextDouble(-radius, radius), random.nextDouble(-radius, radius), random.nextDouble(-radius, radius)).normalize().multiply((random.nextDouble(-radius, radius)) * offset);
        Vector endVector = start.clone().toVector().add(direction.clone().multiply(length)).add(randomizer);
        Location end = endVector.toLocation(start.getWorld());
        if (end.distance(start) <= length) {
            inRange = true;
            continue;
        } else {
            inRange = false;
        }
        int rate = (int) (start.distance(end) / 0.1); // distance * (distance / 10)
        Vector rateDir = endVector.clone().subtract(start.toVector()).normalize().multiply(0.1);
        for (int i = 0; i < rate; i++) {
            Location loc = start.clone().add(rateDir.clone().multiply(i));
            action.accept(loc);
        }
        buildLightning(end.clone(), direction, entries - 1, branches - 1, radius, offset * offsetRate, offsetRate, length * lengthRate, lengthRate, branch * branchRate, branchRate, action);
        if (branches <= 0) {
            break;
        }
    }
}
 
Example 10
Source Project: ForgeHax   File: FancyChat.java    License: MIT License 5 votes vote down vote up
private String makeWave(String message) {
  char[] messageArray = message.toCharArray();
  ThreadLocalRandom rand = ThreadLocalRandom.current();
  double span = rand.nextDouble(0.4D, 1.3D);
  double xoff = rand.nextDouble(0, 32);
  double yoff = rand.nextDouble(-0.4, 0.6);
  
  for (int i = 0; i < messageArray.length; i++) {
    if (waveCharIsUpper(i, span, xoff, yoff)) {
      messageArray[i] = Character.toUpperCase(messageArray[i]);
    }
  }
  return new String(messageArray);
}
 
Example 11
private int randomColor() {
    ThreadLocalRandom random = ThreadLocalRandom.current();
    double rand = random.nextDouble(1, 100);

    if (rand <= 0.164) {
        return DyeColor.PINK.getDyedData();
    }

    if (rand <= 15) {
        return random.nextBoolean() ? DyeColor.BLACK.getDyedData() : random.nextBoolean() ? DyeColor.GRAY.getDyedData() : DyeColor.LIGHT_GRAY.getDyedData();
    }

    return DyeColor.WHITE.getDyedData();
}
 
Example 12
Source Project: Nukkit   File: EntitySheep.java    License: GNU General Public License v3.0 5 votes vote down vote up
private int randomColor() {
    ThreadLocalRandom random = ThreadLocalRandom.current();
    double rand = random.nextDouble(1, 100);

    if (rand <= 0.164) {
        return DyeColor.PINK.getWoolData();
    }

    if (rand <= 15) {
        return random.nextBoolean() ? DyeColor.BLACK.getWoolData() : random.nextBoolean() ? DyeColor.GRAY.getWoolData() : DyeColor.LIGHT_GRAY.getWoolData();
    }

    return DyeColor.WHITE.getWoolData();
}
 
Example 13
/** {@inheritDoc} */
@Override
protected double[] createProbabilities() {
    final double[] probabilities = new double[randomNonUniformSize];
    final ThreadLocalRandom rng = ThreadLocalRandom.current();
    for (int i = 0; i < probabilities.length; i++) {
        probabilities[i] = rng.nextDouble();
    }
    return probabilities;
}
 
Example 14
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 15
Source Project: Nukkit   File: EntitySheep.java    License: GNU General Public License v3.0 5 votes vote down vote up
private int randomColor() {
    ThreadLocalRandom random = ThreadLocalRandom.current();
    double rand = random.nextDouble(1, 100);

    if (rand <= 0.164) {
        return DyeColor.PINK.getWoolData();
    }

    if (rand <= 15) {
        return random.nextBoolean() ? DyeColor.BLACK.getWoolData() : random.nextBoolean() ? DyeColor.GRAY.getWoolData() : DyeColor.LIGHT_GRAY.getWoolData();
    }

    return DyeColor.WHITE.getWoolData();
}
 
Example 16
/** {@inheritDoc} */
@Override public boolean test(Map<Object, Object> ctx) throws Exception {
    ThreadLocalRandom rnd = ThreadLocalRandom.current();

    if (cfg.memberId() % 2 == 0) {
        double salary = rnd.nextDouble() * args.range() * 1000;

        double maxSalary = salary + 1000;

        Collection<Cache.Entry<Integer, Object>> entries = executeQuery(salary, maxSalary);

        for (Cache.Entry<Integer, Object> entry : entries) {
            Person p = (Person)entry.getValue();

            if (p.getSalary() < salary || p.getSalary() > maxSalary)
                throw new Exception("Invalid person retrieved [min=" + salary + ", max=" + maxSalary +
                        ", person=" + p + ']');
        }
    }
    else {
        IgniteCache<Integer, Object> cache = cacheForOperation(true);

        int i = rnd.nextInt(args.range());

        cache.put(i, new Person(i, "firstName" + i, "lastName" + i, i * 1000));
    }

    return true;
}
 
Example 17
/** {@inheritDoc} */
@Override public boolean test(Map<Object, Object> ctx) throws Exception {
    ThreadLocalRandom rnd = ThreadLocalRandom.current();

    IgniteCache<Integer, Object> cache = cacheForOperation(true);

    if (rnd.nextBoolean()) {
        double salary = rnd.nextDouble() * args.range() * 1000;

        double maxSalary = salary + 1000;

        Collection<Cache.Entry<Integer, Object>> entries = executeQuery(salary, maxSalary);

        for (Cache.Entry<Integer, Object> entry : entries) {
            Person p = (Person)entry.getValue();

            if (p.getSalary() < salary || p.getSalary() > maxSalary)
                throw new Exception("Invalid person retrieved [min=" + salary + ", max=" + maxSalary +
                        ", person=" + p + ']');
        }

        qryCnt.getAndIncrement();
    }
    else {
        int i = rnd.nextInt(args.range());

        cache.put(i, new Person(i, "firstName" + i, "lastName" + i, i * 1000));

        putCnt.getAndIncrement();
    }

    return true;
}
 
Example 18
/** {@inheritDoc} */
@Override public boolean test(Map<Object, Object> ctx) throws Exception {
    ThreadLocalRandom rnd = ThreadLocalRandom.current();

    if (rnd.nextBoolean()) {
        double salary = rnd.nextDouble() * args.range() * 1000;

        double maxSalary = salary + 1000;

        Collection<Cache.Entry<Integer, Object>> entries = executeQuery(salary, maxSalary);

        for (Cache.Entry<Integer, Object> entry : entries) {
            Object o = entry.getValue();

            double s = o instanceof Person ? ((Person) o).getSalary() : ((BinaryObject) o).<Double>field("salary");

            if (s < salary || s > maxSalary)
                throw new Exception("Invalid person retrieved [min=" + salary + ", max=" + maxSalary +
                        ", person=" + o + ']');
        }

        qryCnt.getAndIncrement();
    }
    else {
        int i = rnd.nextInt(args.range());

        cache.query(new SqlFieldsQuery("merge into Person(_key, id, firstName, lastName, salary) " +
            "values (?, ?, ?, ?, ?)").setArgs(i, i, "firstName" + i, "lastName" + i, (double) i * 1000));

        putCnt.getAndIncrement();
    }

    return true;
}
 
Example 19
@Override
public void initializeScan(final long stepTime, final int numSteps) {
	final ThreadLocalRandom random = ThreadLocalRandom.current();
	testData = new double[numSteps];
	for (int i = 0; i < testData.length; i++) {
		testData[i] = random.nextDouble(0, Double.MAX_VALUE);
	}

	super.initializeScan(stepTime, numSteps);
}
 
Example 20
Source Project: XSeries   File: XParticle.java    License: MIT License 4 votes vote down vote up
/**
 * Spawns a broken line that creates more and extended branches
 * as it gets closer to the end length.
 * This method doesn't support rotations. Use the direction instead.
 *
 * @param start      the starting point of the new branch. For the first call it's the same location as the displays location.
 * @param direction  the direction of the lightning. A simple direction would be {@code entity.getLocation().getDirection().normalize()}
 *                   For a simple end point direction would be {@code endLocation.toVector().subtract(start.toVector()).normalize()}
 * @param entries    the number of entries for the main lightning branch. Recommended is 20
 * @param branches   the maximum number of branches each entry can have. Recommended is 200
 * @param radius     the radius of the lightning branches. Recommended is 0.5
 * @param offset     the offset of the lightning branches. Recommended is 2
 * @param offsetRate the offset change rate of the lightning branches. Recommended is 1
 * @param length     the length of the lightning branch. Recommended is 1.5
 * @param lengthRate the length change rate of the lightning branch. Recommended is 1
 * @param branch     the chance of creating a new branch. Recommended is 0.1
 * @param branchRate the chance change of creating a new branch. Recommended is 1
 * @since 3.0.0
 */
public static void lightning(Location start, Vector direction, int entries, int branches, double radius,
                             double offset, double offsetRate,
                             double length, double lengthRate,
                             double branch, double branchRate, ParticleDisplay display) {
    ThreadLocalRandom random = ThreadLocalRandom.current();
    if (entries <= 0) return;
    boolean inRange = true;

    // Check if we can create new branches or the current branch
    // length is already in range.
    while (random.nextDouble() < branch || inRange) {
        // Break our straight line randomly.
        Vector randomizer = new Vector(
                random.nextDouble(-radius, radius), random.nextDouble(-radius, radius), random.nextDouble(-radius, radius))
                .normalize().multiply((random.nextDouble(-radius, radius)) * offset);
        Vector endVector = start.clone().toVector().add(direction.clone().multiply(length)).add(randomizer);
        Location end = endVector.toLocation(start.getWorld());

        // Check if the broken line length is in our max length range.
        if (end.distance(start) <= length) {
            inRange = true;
            continue;
        } else inRange = false;

        // Create particle points in our broken straight line.
        int rate = (int) (start.distance(end) / 0.1); // distance * (distance / 10)
        Vector rateDir = endVector.clone().subtract(start.toVector()).normalize().multiply(0.1);
        for (int i = 0; i < rate; i++) {
            Location loc = start.clone().add(rateDir.clone().multiply(i));
            display.spawn(loc);
        }

        // Create new entries if possible.
        lightning(end.clone(), direction, entries - 1, branches - 1, radius, offset * offsetRate, offsetRate,
                length * lengthRate, lengthRate,
                branch * branchRate, branchRate, display);
        // Check if the maximum number of branches has already been used for this entry.
        if (branches <= 0) break;
    }
}