Example usage for java.util Random nextBoolean

List of usage examples for java.util Random nextBoolean

Introduction

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

Prototype

public boolean nextBoolean() 

Source Link

Document

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

Usage

From source file:com.espertech.esper.example.marketdatafeed.FeedSimMain.java

public void run() {
    if (isWaitKeypress) {
        System.out.println("...press enter to start simulation...");
        try {// w  w w .j  av a2 s. c  o m
            System.in.read();
        } catch (IOException e) {
            log.error("Exception reading keyboard input: " + e.getMessage(), e);
        }
    }

    // Configure engine with event names to make the statements more readable.
    // This could also be done in a configuration file.
    Configuration configuration = new Configuration();
    configuration.addEventType("MarketDataEvent", MarketDataEvent.class.getName());

    // Get engine instance
    EPServiceProvider epService = EPServiceProviderManager.getProvider(engineURI, configuration);

    // Set up statements
    TicksPerSecondStatement tickPerSecStmt = new TicksPerSecondStatement(epService.getEPAdministrator());
    tickPerSecStmt.addListener(new RateReportingListener());

    TicksFalloffStatement falloffStmt = new TicksFalloffStatement(epService.getEPAdministrator());
    falloffStmt.addListener(new RateFalloffAlertListener());

    // For continuous non-ending simulation
    if (continuousSimulation) {
        new MarketDataSendRunnable(epService, true).run();
    } else {
        // Send events
        ExecutorService threadPool = Executors.newFixedThreadPool(numberOfThreads);
        MarketDataSendRunnable runnables[] = new MarketDataSendRunnable[numberOfThreads];
        for (int i = 0; i < numberOfThreads; i++) {
            runnables[i] = new MarketDataSendRunnable(epService, false);
            threadPool.submit(runnables[i]);
        }

        int seconds = 0;
        Random random = new Random();
        while (seconds < numSeconds) {
            seconds++;
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                log.info("Interrupted", e);
                break;
            }

            FeedEnum feedToDropOff;
            if (random.nextDouble() * 100 < dropProbability) {
                feedToDropOff = FeedEnum.FEED_A;
                if (random.nextBoolean()) {
                    feedToDropOff = FeedEnum.FEED_B;
                }
                log.info("Setting drop-off for feed " + feedToDropOff);

            } else {
                feedToDropOff = null;
            }
            for (int i = 0; i < runnables.length; i++) {
                runnables[i].setRateDropOffFeed(feedToDropOff);
            }
        }

        log.info("Shutting down threadpool");
        for (int i = 0; i < runnables.length; i++) {
            runnables[i].setShutdown();
        }
        threadPool.shutdown();
        try {
            threadPool.awaitTermination(10, TimeUnit.SECONDS);
        } catch (InterruptedException e) {
            // no action
        }
    }
}

From source file:org.apache.jackrabbit.core.data.ConcurrentGcTest.java

void doTest(DataStore store) throws Exception {
    this.store = store;

    Random r = new Random();

    concurrentGcLoopStart();/*from   www .j  a va  2 s  .c om*/

    int len = 100;
    if (getTestScale() > 1) {
        len = 1000;
    }

    for (int i = 0; i < len && gcException == null; i++) {
        LOG.info("test " + i);
        byte[] data = new byte[3];
        r.nextBytes(data);
        DataRecord rec = store.addRecord(new ByteArrayInputStream(data));
        LOG.debug("  added " + rec.getIdentifier());
        if (r.nextBoolean()) {
            LOG.debug("  added " + rec.getIdentifier() + " -> keep reference");
            ids.add(rec.getIdentifier());
            store.getRecord(rec.getIdentifier());
        }
        if (r.nextInt(100) == 0) {
            LOG.debug("clear i: " + i);
            ids.clear();
        }
    }
    concurrentGcLoopStop();
    store.close();
}

From source file:org.eclipse.recommenders.stacktraces.rcp.actions.LogErrorsAction.java

private void logStressTest() {
    ExecutorService pool = Executors.newFixedThreadPool(200);
    final Random random = new Random();
    for (int i = 0; i < 100000; i++) {
        pool.execute(new Runnable() {

            @Override//  www  .  j  a v a 2s  . c  o  m
            public void run() {
                RuntimeException ex = new IllegalArgumentException("cause");
                StackTraceElement[] trace = createRandomTrace();
                ex.setStackTrace(trace);
                final Status status = new Status(IStatus.ERROR, "org.eclipse.recommenders.stacktraces.rcp",
                        "error", ex);
                if (random.nextBoolean()) {
                    log.log(status);
                } else {
                    if (random.nextBoolean()) {
                        Display.getDefault().syncExec(new ExecuteLog(status));
                    } else {
                        Display.getDefault().asyncExec(new ExecuteLog(status));
                    }
                }
            }
        });
    }
}

From source file:org.apache.jackrabbit.core.data.DataStoreTest.java

void doTest(DataStore ds, int offset) throws Exception {
    ArrayList<DataRecord> list = new ArrayList<DataRecord>();
    HashMap<DataRecord, Integer> map = new HashMap<DataRecord, Integer>();
    for (int i = 0; i < 100; i++) {
        int size = 100 + i * 10;
        RandomInputStream in = new RandomInputStream(size + offset, size);
        DataRecord rec = ds.addRecord(in);
        list.add(rec);//  w w w.  jav a2  s  .c o  m
        map.put(rec, new Integer(size));
    }
    Random random = new Random(1);
    for (int i = 0; i < list.size(); i++) {
        int pos = random.nextInt(list.size());
        DataRecord rec = list.get(pos);
        int size = map.get(rec);
        rec = ds.getRecord(rec.getIdentifier());
        assertEquals(size, rec.getLength());
        InputStream in = rec.getStream();
        RandomInputStream expected = new RandomInputStream(size + offset, size);
        if (random.nextBoolean()) {
            in = readInputStreamRandomly(in, random);
        }
        assertEquals(expected, in);
        in.close();
    }
}

From source file:org.apache.camel.processor.RedeliveryPolicy.java

/**
 * Calculates the new redelivery delay based on the last one
 *
 * @param previousDelay  previous redelivery delay
 * @param redeliveryCounter  number of previous redelivery attempts
 * @return the calculate delay/*ww w.j  a  v a 2  s  .  c  om*/
 */
public long calculateRedeliveryDelay(long previousDelay, int redeliveryCounter) {
    if (ObjectHelper.isNotEmpty(delayPattern)) {
        // calculate delay using the pattern
        return calculateRedeliverDelayUsingPattern(delayPattern, redeliveryCounter);
    }

    // calculate the delay using the conventional parameters
    long redeliveryDelayResult;
    if (previousDelay == 0) {
        redeliveryDelayResult = redeliveryDelay;
    } else if (useExponentialBackOff && backOffMultiplier > 1) {
        redeliveryDelayResult = Math.round(backOffMultiplier * previousDelay);
    } else {
        redeliveryDelayResult = previousDelay;
    }

    if (useCollisionAvoidance) {

        /*
         * First random determines +/-, second random determines how far to
         * go in that direction. -cgs
         */
        Random random = getRandomNumberGenerator();
        double variance = (random.nextBoolean() ? collisionAvoidanceFactor : -collisionAvoidanceFactor)
                * random.nextDouble();
        redeliveryDelayResult += redeliveryDelayResult * variance;
    }

    // ensure the calculated result is not bigger than the max delay (if configured)
    if (maximumRedeliveryDelay > 0 && redeliveryDelayResult > maximumRedeliveryDelay) {
        redeliveryDelayResult = maximumRedeliveryDelay;
    }

    return redeliveryDelayResult;
}

From source file:org.apache.hadoop.net.unix.TestDomainSocketWatcher.java

@Test(timeout = 300000)
public void testStress() throws Exception {
    final int SOCKET_NUM = 250;
    final ReentrantLock lock = new ReentrantLock();
    final DomainSocketWatcher watcher = newDomainSocketWatcher(10000000);
    final ArrayList<DomainSocket[]> pairs = new ArrayList<DomainSocket[]>();
    final AtomicInteger handled = new AtomicInteger(0);

    final Thread adderThread = new Thread(new Runnable() {
        @Override//from  w w w .ja v  a2  s  .  c  om
        public void run() {
            try {
                for (int i = 0; i < SOCKET_NUM; i++) {
                    DomainSocket pair[] = DomainSocket.socketpair();
                    watcher.add(pair[1], new DomainSocketWatcher.Handler() {
                        @Override
                        public boolean handle(DomainSocket sock) {
                            handled.incrementAndGet();
                            return true;
                        }
                    });
                    lock.lock();
                    try {
                        pairs.add(pair);
                    } finally {
                        lock.unlock();
                    }
                }
            } catch (Throwable e) {
                LOG.error(e);
                throw new RuntimeException(e);
            }
        }
    });

    final Thread removerThread = new Thread(new Runnable() {
        @Override
        public void run() {
            final Random random = new Random();
            try {
                while (handled.get() != SOCKET_NUM) {
                    lock.lock();
                    try {
                        if (!pairs.isEmpty()) {
                            int idx = random.nextInt(pairs.size());
                            DomainSocket pair[] = pairs.remove(idx);
                            if (random.nextBoolean()) {
                                pair[0].close();
                            } else {
                                watcher.remove(pair[1]);
                            }
                        }
                    } finally {
                        lock.unlock();
                    }
                }
            } catch (Throwable e) {
                LOG.error(e);
                throw new RuntimeException(e);
            }
        }
    });

    adderThread.start();
    removerThread.start();
    Uninterruptibles.joinUninterruptibly(adderThread);
    Uninterruptibles.joinUninterruptibly(removerThread);
    watcher.close();
}

From source file:com.keke.shop.superbuy.demo.DemoDataGenerator.java

protected void generateReportData() {
    if (generateReportData) {

        // Report data is generated in background thread

        Thread thread = new Thread(new Runnable() {

            public void run() {

                // We need to temporarily disable the job executor or it would interfere with the process execution
                ((ProcessEngineImpl) processEngine).getProcessEngineConfiguration().getJobExecutor().shutdown();

                Random random = new Random();

                Date now = new Date(new Date().getTime() - (24 * 60 * 60 * 1000));
                ((ProcessEngineImpl) processEngine).getProcessEngineConfiguration().getClock()
                        .setCurrentTime(now);

                for (int i = 0; i < 50; i++) {

                    if (random.nextBoolean()) {
                        processEngine.getRuntimeService().startProcessInstanceByKey("fixSystemFailure");
                    }/*from  w  w  w.  ja  v  a2 s .  c o  m*/

                    if (random.nextBoolean()) {
                        processEngine.getIdentityService().setAuthenticatedUserId("kermit");
                        Map<String, Object> variables = new HashMap<String, Object>();
                        variables.put("customerName", "testCustomer");
                        variables.put("details", "Looks very interesting!");
                        variables.put("notEnoughInformation", false);
                        processEngine.getRuntimeService().startProcessInstanceByKey("reviewSaledLead",
                                variables);
                    }

                    if (random.nextBoolean()) {
                        processEngine.getRuntimeService().startProcessInstanceByKey("escalationExample");
                    }

                    if (random.nextInt(100) < 20) {
                        now = new Date(now.getTime() - ((24 * 60 * 60 * 1000) - (60 * 60 * 1000)));
                        ((ProcessEngineImpl) processEngine).getProcessEngineConfiguration().getClock()
                                .setCurrentTime(now);
                    }
                }

                List<Job> jobs = processEngine.getManagementService().createJobQuery().list();
                for (int i = 0; i < jobs.size() / 2; i++) {
                    ((ProcessEngineImpl) processEngine).getProcessEngineConfiguration().getClock()
                            .setCurrentTime(jobs.get(i).getDuedate());
                    processEngine.getManagementService().executeJob(jobs.get(i).getId());
                }

                List<Task> tasks = processEngine.getTaskService().createTaskQuery().list();
                while (tasks.size() > 0) {
                    for (Task task : tasks) {

                        if (task.getAssignee() == null) {
                            String assignee = random.nextBoolean() ? "kermit" : "fozzie";
                            processEngine.getTaskService().claim(task.getId(), assignee);
                        }

                        ((ProcessEngineImpl) processEngine).getProcessEngineConfiguration().getClock()
                                .setCurrentTime(new Date(
                                        task.getCreateTime().getTime() + random.nextInt(60 * 60 * 1000)));

                        processEngine.getTaskService().complete(task.getId());
                    }

                    tasks = processEngine.getTaskService().createTaskQuery().list();
                }

                ((ProcessEngineImpl) processEngine).getProcessEngineConfiguration().getClock().reset();

                ((ProcessEngineImpl) processEngine).getProcessEngineConfiguration().getJobExecutor().start();
                LOGGER.info("Demo report data generated");
            }

        });
        thread.start();

    }
}

From source file:org.apache.hadoop.net.unix.TestDomainSocketWatcher.java

@Test(timeout = 300000)
public void testStressInterruption() throws Exception {
    final int SOCKET_NUM = 250;
    final ReentrantLock lock = new ReentrantLock();
    final DomainSocketWatcher watcher = newDomainSocketWatcher(10);
    final ArrayList<DomainSocket[]> pairs = new ArrayList<DomainSocket[]>();
    final AtomicInteger handled = new AtomicInteger(0);

    final Thread adderThread = new Thread(new Runnable() {
        @Override//  ww w .jav  a  2  s .co m
        public void run() {
            try {
                for (int i = 0; i < SOCKET_NUM; i++) {
                    DomainSocket pair[] = DomainSocket.socketpair();
                    watcher.add(pair[1], new DomainSocketWatcher.Handler() {
                        @Override
                        public boolean handle(DomainSocket sock) {
                            handled.incrementAndGet();
                            return true;
                        }
                    });
                    lock.lock();
                    try {
                        pairs.add(pair);
                    } finally {
                        lock.unlock();
                    }
                    TimeUnit.MILLISECONDS.sleep(1);
                }
            } catch (Throwable e) {
                LOG.error(e);
                throw new RuntimeException(e);
            }
        }
    });

    final Thread removerThread = new Thread(new Runnable() {
        @Override
        public void run() {
            final Random random = new Random();
            try {
                while (handled.get() != SOCKET_NUM) {
                    lock.lock();
                    try {
                        if (!pairs.isEmpty()) {
                            int idx = random.nextInt(pairs.size());
                            DomainSocket pair[] = pairs.remove(idx);
                            if (random.nextBoolean()) {
                                pair[0].close();
                            } else {
                                watcher.remove(pair[1]);
                            }
                            TimeUnit.MILLISECONDS.sleep(1);
                        }
                    } finally {
                        lock.unlock();
                    }
                }
            } catch (Throwable e) {
                LOG.error(e);
                throw new RuntimeException(e);
            }
        }
    });

    adderThread.start();
    removerThread.start();
    TimeUnit.MILLISECONDS.sleep(100);
    watcher.watcherThread.interrupt();
    Uninterruptibles.joinUninterruptibly(adderThread);
    Uninterruptibles.joinUninterruptibly(removerThread);
    Uninterruptibles.joinUninterruptibly(watcher.watcherThread);
}

From source file:dremel.common.AvroTest.java

private void generateRandomOrecSchemaRecursive(StringBuffer schema, Random random, int depth) {
    // we are here under a record and record may have other records, arrays
    // or scalara as children
    for (int i = 5; i >= 0; i--) {
        // array?
        if ((depth-- > 0) || (random.nextBoolean() && random.nextBoolean() && random.nextBoolean())) {
            generateRandomSchemaForArray(schema, random);
            if (random.nextBoolean()) {
                generateRandomSchemaForArrayedRecord(schema, random);
                generateRandomOrecSchemaRecursive(schema, random, depth);
                schema.append("]}");
            } else if (random.nextBoolean())
                generateRandomSchemaForScalar(schema, random, "int");
            else/* w ww.java 2  s.  com*/
                generateRandomSchemaForScalar(schema, random, "string");
            schema.append("}}");
        } else if (((depth > 0)) && random.nextBoolean() && random.nextBoolean()) { // record?
            generateRandomSchemaForRecord(schema, random);
            generateRandomOrecSchemaRecursive(schema, random, depth);
            schema.append("]}}");
        } else { // scalar?
            if (random.nextBoolean())
                generateRandomSchemaForScalar(schema, random, "int");
            else
                generateRandomSchemaForScalar(schema, random, "string");
        }
        if (i > 0)
            schema.append(',');
    }
}

From source file:de.rrze.idmone.utils.jpwgen.PwGenerator.java

/**
 * The real password generation is performed in this method
 * /*w  w  w  .j  a  v a 2  s  .com*/
 * @param size
 *            the length of the password
 * @param pw_flags
 *            the settings for the password
 * @return the newly created password
 */
private synchronized static String phonemes(int size, int pw_flags, Random random) {
    int c, i, len, flags, feature_flags;
    int prev, should_be;
    boolean first;
    String str;
    char ch;
    StringBuffer buf = new StringBuffer();

    do {
        buf.delete(0, buf.length());
        feature_flags = pw_flags;
        c = 0;
        prev = 0;
        should_be = 0;
        first = true;
        should_be = random.nextBoolean() ? VOWEL : CONSONANT;

        while (c < size) {

            i = random.nextInt(PW_ELEMENTS.length);
            str = PW_ELEMENTS[i].getValue();
            len = str.length();
            flags = PW_ELEMENTS[i].getType();
            /* Filter on the basic type of the next element */
            if ((flags & should_be) == 0) {
                continue;
            }
            /* Handle the NOT_FIRST flag */
            if (first && ((flags & NOT_FIRST) != 0))
                continue;
            /* Don't allow VOWEL followed a Vowel/Dipthong pair */
            if (((prev & VOWEL) != 0) && ((flags & VOWEL) != 0) && ((flags & DIPTHONG) != 0))
                continue;
            /* Don't allow us to overflow the buffer */
            if (len > size - c)
                continue;
            /*
             * OK, we found an element which matches our criteria, let's do
             * it!
             */
            buf.append(str);

            c += len;
            /* Handle the AMBIGUOUS flag */
            if ((pw_flags & PW_AMBIGUOUS) != 0) {
                int k = -1;
                for (int j = 0; j < PW_AMBIGUOUS_SYMBOLS.length(); j++) {
                    k = buf.indexOf(String.valueOf(PW_AMBIGUOUS_SYMBOLS.charAt(j)));
                    if (k != -1)
                        break;
                }
                if (k != -1) {
                    buf.delete(k, buf.length());
                    c = buf.length();
                }
            }

            /* Time to stop? */
            if (c >= size) {
                // System.out.println("BREAK 1: "+c + " - "+size);
                break;
            }
            /*
             * Handle PW_DIGITS
             */
            if ((pw_flags & PW_DIGITS) != 0) {
                if (!first && (random.nextInt(10) < 3)) {
                    do {
                        ch = (new Integer(random.nextInt(10))).toString().charAt(0);
                    } while (((pw_flags & PW_AMBIGUOUS) != 0) && (PW_AMBIGUOUS_SYMBOLS.indexOf(ch) != -1));
                    c++;
                    buf = buf.append(ch);
                    feature_flags &= ~PW_DIGITS;

                    first = true;
                    prev = 0;
                    should_be = random.nextBoolean() ? VOWEL : CONSONANT;
                    continue;
                }
            }

            /* Handle PW_SYMBOLS */
            if ((pw_flags & PW_SYMBOLS) != 0) {
                if (!first && (random.nextInt(10) < 2)) {
                    do {
                        ch = PW_SPECIAL_SYMBOLS.charAt(random.nextInt(PW_SPECIAL_SYMBOLS.length()));
                    } while (((pw_flags & PW_AMBIGUOUS) != 0) && (PW_AMBIGUOUS_SYMBOLS.indexOf(ch) != -1));
                    c++;
                    buf = buf.append(ch);
                    feature_flags &= ~PW_SYMBOLS;
                }
            } else if ((pw_flags & PW_SYMBOLS_REDUCED) != 0) {
                if (!first && (random.nextInt(10) < 2)) {
                    do {
                        ch = PW_SPECIAL_SYMBOLS_REDUCED
                                .charAt(random.nextInt(PW_SPECIAL_SYMBOLS_REDUCED.length()));
                    } while (((pw_flags & PW_AMBIGUOUS) != 0) && (PW_AMBIGUOUS_SYMBOLS.indexOf(ch) != -1));
                    c++;
                    buf = buf.append(ch);
                    feature_flags &= ~PW_SYMBOLS_REDUCED;
                }
            }

            /* Handle PW_UPPERS */
            if ((pw_flags & PW_UPPERS) != 0) {
                if ((first || ((flags & CONSONANT) != 0)) && (random.nextInt(10) < 2)) {
                    int lastChar = buf.length() - 1;
                    buf.setCharAt(lastChar, Character.toUpperCase(buf.charAt(lastChar)));
                    feature_flags &= ~PW_UPPERS;
                }
            }

            /*
             * OK, figure out what the next element should be
             */
            if (should_be == CONSONANT) {
                should_be = VOWEL;
            } else { /* should_be == VOWEL */
                if (((prev & VOWEL) != 0) || ((flags & DIPTHONG) != 0) || (random.nextInt(10) > 3))
                    should_be = CONSONANT;
                else
                    should_be = VOWEL;
            }
            prev = flags;
            first = false;

        }
    } while ((feature_flags & (PW_UPPERS | PW_DIGITS | PW_SYMBOLS | PW_SYMBOLS_REDUCED)) != 0);

    return buf.toString();
}