Example usage for java.util Random nextLong

List of usage examples for java.util Random nextLong

Introduction

In this page you can find the example usage for java.util Random nextLong.

Prototype

public long nextLong() 

Source Link

Document

Returns the next pseudorandom, uniformly distributed long value from this random number generator's sequence.

Usage

From source file:Main.java

public static void main(String[] argv) throws Exception {
    Random rand = new Random();
    long seed = rand.nextLong();
    rand = new Random(seed);
    Random rand2 = new Random(seed);
}

From source file:Main.java

public static void main(String[] argv) throws Exception {

    Random rand = new Random();

    boolean b = rand.nextBoolean();
    long l = rand.nextLong();
    float f = rand.nextFloat(); // 0.0 <= f < 1.0
    double d = rand.nextDouble(); // 0.0 <= d < 1.0
}

From source file:Main.java

public static void main(String args[]) {

    Random randomno = new Random();

    // get next long value 
    long value = randomno.nextLong();

    // check the value  
    System.out.println("Long value is: " + value);
}

From source file:com.yahoo.ads.pb.mttf.PistachiosMTTFTest.java

public static void main(String[] args) {
    PistachiosClient client;//from  w w  w  .  ja va2s  . co m
    try {
        client = new PistachiosClient();
    } catch (Exception e) {
        logger.info("error creating client", e);
        return;
    }
    Random rand = new Random();

    while (true) {
        try {
            long id = rand.nextLong();
            String value = InetAddress.getLocalHost().getHostName() + rand.nextInt();
            client.store(0, id, value.getBytes());
            for (int i = 0; i < 30; i++) {
                byte[] clientValue = client.lookup(0, id);
                String remoteValue = new String(clientValue);
                if (Arrays.equals(value.getBytes(), clientValue)
                        || !remoteValue.contains(InetAddress.getLocalHost().getHostName())) {
                    logger.debug("succeeded checking id {} value {}", id, value);
                } else {
                    logger.error("failed checking id {} value {} != {}", id, value, new String(clientValue));
                    System.exit(0);
                }
                Thread.sleep(100);
            }
        } catch (Exception e) {
            System.out.println("error testing" + e);
            System.exit(0);
        }
    }
}

From source file:hyperloglog.tools.HyperLogLogCLI.java

public static void main(String[] args) {
    Options options = new Options();
    addOptions(options);// w ww. j a v  a 2s.c o  m

    CommandLineParser parser = new BasicParser();
    CommandLine cli = null;
    long n = 0;
    long seed = 123;
    EncodingType enc = EncodingType.SPARSE;
    int p = 14;
    int hb = 64;
    boolean bitPack = true;
    boolean noBias = true;
    int unique = -1;
    String filePath = null;
    BufferedReader br = null;
    String outFile = null;
    String inFile = null;
    FileOutputStream fos = null;
    DataOutputStream out = null;
    FileInputStream fis = null;
    DataInputStream in = null;
    try {
        cli = parser.parse(options, args);

        if (!(cli.hasOption('n') || cli.hasOption('f') || cli.hasOption('d'))) {
            System.out.println("Example usage: hll -n 1000 " + "<OR> hll -f /tmp/input.txt "
                    + "<OR> hll -d -i /tmp/out.hll");
            usage(options);
            return;
        }

        if (cli.hasOption('n')) {
            n = Long.parseLong(cli.getOptionValue('n'));
        }

        if (cli.hasOption('e')) {
            String value = cli.getOptionValue('e');
            if (value.equals(EncodingType.DENSE.name())) {
                enc = EncodingType.DENSE;
            }
        }

        if (cli.hasOption('p')) {
            p = Integer.parseInt(cli.getOptionValue('p'));
            if (p < 4 && p > 16) {
                System.out.println("Warning! Out-of-range value specified for p. Using to p=14.");
                p = 14;
            }
        }

        if (cli.hasOption('h')) {
            hb = Integer.parseInt(cli.getOptionValue('h'));
        }

        if (cli.hasOption('c')) {
            noBias = Boolean.parseBoolean(cli.getOptionValue('c'));
        }

        if (cli.hasOption('b')) {
            bitPack = Boolean.parseBoolean(cli.getOptionValue('b'));
        }

        if (cli.hasOption('f')) {
            filePath = cli.getOptionValue('f');
            br = new BufferedReader(new FileReader(new File(filePath)));
        }

        if (filePath != null && cli.hasOption('n')) {
            System.out.println("'-f' (input file) specified. Ignoring -n.");
        }

        if (cli.hasOption('s')) {
            if (cli.hasOption('o')) {
                outFile = cli.getOptionValue('o');
                fos = new FileOutputStream(new File(outFile));
                out = new DataOutputStream(fos);
            } else {
                System.err.println("Specify output file. Example usage: hll -s -o /tmp/out.hll");
                usage(options);
                return;
            }
        }

        if (cli.hasOption('d')) {
            if (cli.hasOption('i')) {
                inFile = cli.getOptionValue('i');
                fis = new FileInputStream(new File(inFile));
                in = new DataInputStream(fis);
            } else {
                System.err.println("Specify input file. Example usage: hll -d -i /tmp/in.hll");
                usage(options);
                return;
            }
        }

        // return after deserialization
        if (fis != null && in != null) {
            long start = System.currentTimeMillis();
            HyperLogLog deserializedHLL = HyperLogLogUtils.deserializeHLL(in);
            long end = System.currentTimeMillis();
            System.out.println(deserializedHLL.toString());
            System.out.println("Count after deserialization: " + deserializedHLL.count());
            System.out.println("Deserialization time: " + (end - start) + " ms");
            return;
        }

        // construct hll and serialize it if required
        HyperLogLog hll = HyperLogLog.builder().enableBitPacking(bitPack).enableNoBias(noBias).setEncoding(enc)
                .setNumHashBits(hb).setNumRegisterIndexBits(p).build();

        if (br != null) {
            Set<String> hashset = new HashSet<String>();
            String line;
            while ((line = br.readLine()) != null) {
                hll.addString(line);
                hashset.add(line);
            }
            n = hashset.size();
        } else {
            Random rand = new Random(seed);
            for (int i = 0; i < n; i++) {
                if (unique < 0) {
                    hll.addLong(rand.nextLong());
                } else {
                    int val = rand.nextInt(unique);
                    hll.addLong(val);
                }
            }
        }

        long estCount = hll.count();
        System.out.println("Actual count: " + n);
        System.out.println(hll.toString());
        System.out.println("Relative error: " + HyperLogLogUtils.getRelativeError(n, estCount) + "%");
        if (fos != null && out != null) {
            long start = System.currentTimeMillis();
            HyperLogLogUtils.serializeHLL(out, hll);
            long end = System.currentTimeMillis();
            System.out.println("Serialized hyperloglog to " + outFile);
            System.out.println("Serialized size: " + out.size() + " bytes");
            System.out.println("Serialization time: " + (end - start) + " ms");
            out.close();
        }
    } catch (ParseException e) {
        System.err.println("Invalid parameter.");
        usage(options);
    } catch (NumberFormatException e) {
        System.err.println("Invalid type for parameter.");
        usage(options);
    } catch (FileNotFoundException e) {
        System.err.println("Specified file not found.");
        usage(options);
    } catch (IOException e) {
        System.err.println("Exception occured while reading file.");
        usage(options);
    }
}

From source file:backup.store.ExternalExtendedBlockSort.java

public static void main(String[] args) throws Exception {
    Configuration conf = new Configuration();
    Path dir = new Path("file:///home/apm/Development/git-projects/hdfs-backup/hdfs-backup-core/tmp");
    dir.getFileSystem(conf).delete(dir, true);
    long start = System.nanoTime();
    try (ExternalExtendedBlockSort<LongWritable> sort = new ExternalExtendedBlockSort<>(conf, dir,
            LongWritable.class)) {
        Random random = new Random();
        for (int bp = 0; bp < 1; bp++) {
            String bpid = UUID.randomUUID().toString();
            for (int i = 0; i < 10000000; i++) {
                // for (int i = 0; i < 10; i++) {
                long genstamp = random.nextInt(20000);
                long blockId = random.nextLong();
                ExtendedBlock extendedBlock = new ExtendedBlock(bpid, blockId,
                        random.nextInt(Integer.MAX_VALUE), genstamp);
                sort.add(extendedBlock, new LongWritable(blockId));
            }//from w  w  w . java2s .  co  m
        }
        System.out.println("finished");
        sort.finished();
        System.out.println("interate");
        for (String blockPoolId : sort.getBlockPoolIds()) {
            ExtendedBlockEnum<LongWritable> blockEnum = sort.getBlockEnum(blockPoolId);
            ExtendedBlock block;
            long l = 0;
            while ((block = blockEnum.next()) != null) {
                // System.out.println(block);
                long blockId = block.getBlockId();
                l += blockId;
                LongWritable currentValue = blockEnum.currentValue();
                if (currentValue.get() != blockId) {
                    System.err.println("Error " + blockId);
                }
            }
            System.out.println(l);
        }
    }
    long end = System.nanoTime();
    System.out.println("Time [" + (end - start) / 1000000.0 + " ms]");
}

From source file:org.caffinitas.ohc.benchmark.BenchmarkOHC.java

public static void main(String[] args) throws Exception {
    Locale.setDefault(Locale.ENGLISH);
    Locale.setDefault(Locale.Category.FORMAT, Locale.ENGLISH);

    try {/*from   w w  w  .ja  va2s .c o m*/
        CommandLine cmd = parseArguments(args);

        String[] warmUp = cmd.getOptionValue(WARM_UP, "15,5").split(",");
        int warmUpSecs = Integer.parseInt(warmUp[0]);
        int coldSleepSecs = Integer.parseInt(warmUp[1]);

        int duration = Integer.parseInt(cmd.getOptionValue(DURATION, "60"));
        int cores = Runtime.getRuntime().availableProcessors();
        if (cores >= 8)
            cores -= 2;
        else if (cores > 2)
            cores--;
        int threads = Integer.parseInt(cmd.getOptionValue(THREADS, Integer.toString(cores)));
        long capacity = Long.parseLong(cmd.getOptionValue(CAPACITY, "" + (1024 * 1024 * 1024)));
        int hashTableSize = Integer.parseInt(cmd.getOptionValue(HASH_TABLE_SIZE, "0"));
        int segmentCount = Integer.parseInt(cmd.getOptionValue(SEGMENT_COUNT, "0"));
        float loadFactor = Float.parseFloat(cmd.getOptionValue(LOAD_FACTOR, "0"));
        int keyLen = Integer.parseInt(cmd.getOptionValue(KEY_LEN, "0"));
        int chunkSize = Integer.parseInt(cmd.getOptionValue(CHUNK_SIZE, "-1"));
        int fixedKeySize = Integer.parseInt(cmd.getOptionValue(FIXED_KEY_SIZE, "-1"));
        int fixedValueSize = Integer.parseInt(cmd.getOptionValue(FIXED_VALUE_SIZE, "-1"));
        int maxEntrySize = Integer.parseInt(cmd.getOptionValue(MAX_ENTRY_SIZE, "-1"));
        boolean unlocked = Boolean.parseBoolean(cmd.getOptionValue(UNLOCKED, "false"));
        HashAlgorithm hashMode = HashAlgorithm.valueOf(cmd.getOptionValue(HASH_MODE, "MURMUR3"));

        boolean bucketHistogram = Boolean.parseBoolean(cmd.getOptionValue(BUCKET_HISTOGRAM, "false"));

        double readWriteRatio = Double.parseDouble(cmd.getOptionValue(READ_WRITE_RATIO, ".5"));

        Driver[] drivers = new Driver[threads];
        Random rnd = new Random();
        String readKeyDistStr = cmd.getOptionValue(READ_KEY_DIST, DEFAULT_KEY_DIST);
        String writeKeyDistStr = cmd.getOptionValue(WRITE_KEY_DIST, DEFAULT_KEY_DIST);
        String valueSizeDistStr = cmd.getOptionValue(VALUE_SIZE_DIST, DEFAULT_VALUE_SIZE_DIST);
        DistributionFactory readKeyDist = OptionDistribution.get(readKeyDistStr);
        DistributionFactory writeKeyDist = OptionDistribution.get(writeKeyDistStr);
        DistributionFactory valueSizeDist = OptionDistribution.get(valueSizeDistStr);
        for (int i = 0; i < threads; i++) {
            drivers[i] = new Driver(readKeyDist.get(), writeKeyDist.get(), valueSizeDist.get(), readWriteRatio,
                    rnd.nextLong());
        }

        printMessage("Initializing OHC cache...");
        OHCacheBuilder<Long, byte[]> builder = OHCacheBuilder.<Long, byte[]>newBuilder()
                .keySerializer(
                        keyLen <= 0 ? BenchmarkUtils.longSerializer : new BenchmarkUtils.KeySerializer(keyLen))
                .valueSerializer(BenchmarkUtils.serializer).capacity(capacity);
        if (cmd.hasOption(LOAD_FACTOR))
            builder.loadFactor(loadFactor);
        if (cmd.hasOption(SEGMENT_COUNT))
            builder.segmentCount(segmentCount);
        if (cmd.hasOption(HASH_TABLE_SIZE))
            builder.hashTableSize(hashTableSize);
        if (cmd.hasOption(CHUNK_SIZE))
            builder.chunkSize(chunkSize);
        if (cmd.hasOption(MAX_ENTRY_SIZE))
            builder.maxEntrySize(maxEntrySize);
        if (cmd.hasOption(UNLOCKED))
            builder.unlocked(unlocked);
        if (cmd.hasOption(HASH_MODE))
            builder.hashMode(hashMode);
        if (cmd.hasOption(FIXED_KEY_SIZE))
            builder.fixedEntrySize(fixedKeySize, fixedValueSize);

        Shared.cache = builder.build();

        printMessage("Cache configuration: instance       : %s%n" + "                     hash-table-size: %d%n"
                + "                     load-factor    : %.3f%n" + "                     segments       : %d%n"
                + "                     capacity       : %d%n", Shared.cache, Shared.cache.hashTableSizes()[0],
                Shared.cache.loadFactor(), Shared.cache.segments(), Shared.cache.capacity());

        String csvFileName = cmd.getOptionValue(CSV, null);
        PrintStream csv = null;
        if (csvFileName != null) {
            File csvFile = new File(csvFileName);
            csv = new PrintStream(new FileOutputStream(csvFile));
            csv.println("# OHC benchmark - http://github.com/snazy/ohc");
            csv.println("# ");
            csv.printf("# started on %s (%s)%n", InetAddress.getLocalHost().getHostName(),
                    InetAddress.getLocalHost().getHostAddress());
            csv.println("# ");
            csv.printf("# Warum-up/sleep seconds:   %d / %d%n", warmUpSecs, coldSleepSecs);
            csv.printf("# Duration:                 %d seconds%n", duration);
            csv.printf("# Threads:                  %d%n", threads);
            csv.printf("# Capacity:                 %d bytes%n", capacity);
            csv.printf("# Read/Write Ratio:         %f%n", readWriteRatio);
            csv.printf("# Segment Count:            %d%n", segmentCount);
            csv.printf("# Hash table size:          %d%n", hashTableSize);
            csv.printf("# Load Factor:              %f%n", loadFactor);
            csv.printf("# Additional key len:       %d%n", keyLen);
            csv.printf("# Read key distribution:    '%s'%n", readKeyDistStr);
            csv.printf("# Write key distribution:   '%s'%n", writeKeyDistStr);
            csv.printf("# Value size distribution:  '%s'%n", valueSizeDistStr);
            csv.printf("# Type: %s%n", Shared.cache.getClass().getName());
            csv.println("# ");
            csv.printf("# started at %s%n", new Date());
            Properties props = System.getProperties();
            csv.printf("# java.version:             %s%n", props.get("java.version"));
            for (Map.Entry<Object, Object> e : props.entrySet()) {
                String k = (String) e.getKey();
                if (k.startsWith("org.caffinitas.ohc."))
                    csv.printf("# %s: %s%n", k, e.getValue());
            }
            csv.printf("# number of cores: %d%n", Runtime.getRuntime().availableProcessors());
            csv.println("# ");
            csv.println("\"runtime\";" + "\"r_count\";"
                    + "\"r_oneMinuteRate\";\"r_fiveMinuteRate\";\"r_fifteenMinuteRate\";\"r_meanRate\";"
                    + "\"r_snapMin\";\"r_snapMax\";\"r_snapMean\";\"r_snapStdDev\";"
                    + "\"r_snap75\";\"r_snap95\";\"r_snap98\";\"r_snap99\";\"r_snap999\";\"r_snapMedian\";"
                    + "\"w_count\";"
                    + "\"w_oneMinuteRate\";\"w_fiveMinuteRate\";\"w_fifteenMinuteRate\";\"w_meanRate\";"
                    + "\"w_snapMin\";\"w_snapMax\";\"w_snapMean\";\"w_snapStdDev\";"
                    + "\"w_snap75\";\"w_snap95\";\"w_snap98\";\"w_snap99\";\"w_snap999\";\"w_snapMedian\"");
        }

        printMessage(
                "Starting benchmark with%n" + "   threads     : %d%n" + "   warm-up-secs: %d%n"
                        + "   idle-secs   : %d%n" + "   runtime-secs: %d%n",
                threads, warmUpSecs, coldSleepSecs, duration);

        ThreadPoolExecutor main = new ThreadPoolExecutor(threads, threads, coldSleepSecs + 1, TimeUnit.SECONDS,
                new LinkedBlockingQueue<Runnable>(), new ThreadFactory() {
                    volatile int threadNo;

                    public Thread newThread(Runnable r) {
                        return new Thread(r, "driver-main-" + threadNo++);
                    }
                });
        main.prestartAllCoreThreads();

        // warm up

        if (warmUpSecs > 0) {
            printMessage("Start warm-up...");
            runFor(warmUpSecs, main, drivers, bucketHistogram, csv);
            printMessage("");
            logMemoryUse();

            if (csv != null)
                csv.println("# warm up complete");
        }
        // cold sleep

        if (coldSleepSecs > 0) {
            printMessage("Warm up complete, sleep for %d seconds...", coldSleepSecs);
            Thread.sleep(coldSleepSecs * 1000L);
        }

        // benchmark

        printMessage("Start benchmark...");
        runFor(duration, main, drivers, bucketHistogram, csv);
        printMessage("");
        logMemoryUse();

        if (csv != null)
            csv.println("# benchmark complete");

        // finish

        if (csv != null)
            csv.close();

        System.exit(0);
    } catch (Throwable t) {
        t.printStackTrace();
        System.exit(1);
    }
}

From source file:org.opendedup.collections.ShardedProgressiveFileBasedCSMap.java

public static void main(String[] args) throws Exception {
    ShardedProgressiveFileBasedCSMap b = new ShardedProgressiveFileBasedCSMap();
    b.init(1000000, "/opt/sdfs/hash", .001);
    long start = System.currentTimeMillis();
    Random rnd = new Random();
    byte[] hash = null;
    long val = -33;
    byte[] hash1 = null;
    long val1 = -33;
    Tiger16HashEngine eng = new Tiger16HashEngine();
    for (int i = 0; i < 60000; i++) {
        byte[] z = new byte[64];
        rnd.nextBytes(z);//from w  ww . j a v a  2  s .c  o  m
        hash = eng.getHash(z);
        val = rnd.nextLong();
        if (i == 1) {
            val1 = val;
            hash1 = hash;
        }
        if (val < 0)
            val = val * -1;
        ChunkData cm = new ChunkData(hash, val);
        InsertRecord k = b.put(cm);
        if (k.getInserted())
            System.out.println("Unable to add this " + k);

    }
    long end = System.currentTimeMillis();
    System.out.println("Took " + (end - start) / 1000 + " s " + val1);
    System.out.println("Took " + (System.currentTimeMillis() - end) / 1000 + " ms at pos " + b.get(hash1));
    b.claimRecords(SDFSEvent.gcInfoEvent("testing 123"));
    b.close();

}

From source file:Main.java

public static long nextLong(int lower, int upper) {
    Random ra = new Random();
    int n = lower + ra.nextInt(upper - lower);
    long m = ra.nextLong();
    return n + m;
}

From source file:es.emergya.actions.Authentication.java

private static Long nextId() {
    Random r = new Random();
    return r.nextLong();
}