Example usage for java.util.concurrent.atomic AtomicBoolean get

List of usage examples for java.util.concurrent.atomic AtomicBoolean get

Introduction

In this page you can find the example usage for java.util.concurrent.atomic AtomicBoolean get.

Prototype

public final boolean get() 

Source Link

Document

Returns the current value, with memory effects as specified by VarHandle#getVolatile .

Usage

From source file:org.apache.pulsar.testclient.ManagedLedgerWriter.java

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

    final Arguments arguments = new Arguments();
    JCommander jc = new JCommander(arguments);
    jc.setProgramName("pulsar-perf-producer");

    try {/*from w w w.  j  a va 2  s. c o  m*/
        jc.parse(args);
    } catch (ParameterException e) {
        System.out.println(e.getMessage());
        jc.usage();
        System.exit(-1);
    }

    if (arguments.help) {
        jc.usage();
        System.exit(-1);
    }

    arguments.testTime = TimeUnit.SECONDS.toMillis(arguments.testTime);

    // Dump config variables
    ObjectMapper m = new ObjectMapper();
    ObjectWriter w = m.writerWithDefaultPrettyPrinter();
    log.info("Starting Pulsar managed-ledger perf writer with config: {}", w.writeValueAsString(arguments));

    byte[] payloadData = new byte[arguments.msgSize];
    ByteBuf payloadBuffer = PooledByteBufAllocator.DEFAULT.directBuffer(arguments.msgSize);
    payloadBuffer.writerIndex(arguments.msgSize);

    // Now processing command line arguments
    String managedLedgerPrefix = "test-" + DigestUtils.sha1Hex(UUID.randomUUID().toString()).substring(0, 5);

    ClientConfiguration bkConf = new ClientConfiguration();
    bkConf.setUseV2WireProtocol(true);
    bkConf.setAddEntryTimeout(30);
    bkConf.setReadEntryTimeout(30);
    bkConf.setThrottleValue(0);
    bkConf.setNumChannelsPerBookie(arguments.maxConnections);
    bkConf.setZkServers(arguments.zookeeperServers);

    ManagedLedgerFactoryConfig mlFactoryConf = new ManagedLedgerFactoryConfig();
    mlFactoryConf.setMaxCacheSize(0);
    ManagedLedgerFactory factory = new ManagedLedgerFactoryImpl(bkConf, mlFactoryConf);

    ManagedLedgerConfig mlConf = new ManagedLedgerConfig();
    mlConf.setEnsembleSize(arguments.ensembleSize);
    mlConf.setWriteQuorumSize(arguments.writeQuorum);
    mlConf.setAckQuorumSize(arguments.ackQuorum);
    mlConf.setMinimumRolloverTime(10, TimeUnit.MINUTES);
    mlConf.setMetadataEnsembleSize(arguments.ensembleSize);
    mlConf.setMetadataWriteQuorumSize(arguments.writeQuorum);
    mlConf.setMetadataAckQuorumSize(arguments.ackQuorum);
    mlConf.setDigestType(arguments.digestType);
    mlConf.setMaxSizePerLedgerMb(2048);

    List<CompletableFuture<ManagedLedger>> futures = new ArrayList<>();

    for (int i = 0; i < arguments.numManagedLedgers; i++) {
        String name = String.format("%s-%03d", managedLedgerPrefix, i);
        CompletableFuture<ManagedLedger> future = new CompletableFuture<>();
        futures.add(future);
        factory.asyncOpen(name, mlConf, new OpenLedgerCallback() {

            @Override
            public void openLedgerComplete(ManagedLedger ledger, Object ctx) {
                future.complete(ledger);
            }

            @Override
            public void openLedgerFailed(ManagedLedgerException exception, Object ctx) {
                future.completeExceptionally(exception);
            }
        }, null);
    }

    List<ManagedLedger> managedLedgers = futures.stream().map(CompletableFuture::join)
            .collect(Collectors.toList());

    log.info("Created {} managed ledgers", managedLedgers.size());

    Runtime.getRuntime().addShutdownHook(new Thread() {
        public void run() {
            printAggregatedStats();
        }
    });

    Collections.shuffle(managedLedgers);
    AtomicBoolean isDone = new AtomicBoolean();

    List<List<ManagedLedger>> managedLedgersPerThread = Lists.partition(managedLedgers,
            Math.max(1, managedLedgers.size() / arguments.numThreads));

    for (int i = 0; i < arguments.numThreads; i++) {
        List<ManagedLedger> managedLedgersForThisThread = managedLedgersPerThread.get(i);
        int nunManagedLedgersForThisThread = managedLedgersForThisThread.size();
        long numMessagesForThisThread = arguments.numMessages / arguments.numThreads;
        int maxOutstandingForThisThread = arguments.maxOutstanding;

        executor.submit(() -> {
            try {
                final double msgRate = arguments.msgRate / (double) arguments.numThreads;
                final RateLimiter rateLimiter = RateLimiter.create(msgRate);

                // Acquire 1 sec worth of messages to have a slower ramp-up
                rateLimiter.acquire((int) msgRate);
                final long startTime = System.currentTimeMillis();

                final Semaphore semaphore = new Semaphore(maxOutstandingForThisThread);

                final AddEntryCallback addEntryCallback = new AddEntryCallback() {
                    @Override
                    public void addComplete(Position position, Object ctx) {
                        long sendTime = (Long) (ctx);
                        messagesSent.increment();
                        bytesSent.add(payloadData.length);

                        long latencyMicros = NANOSECONDS.toMicros(System.nanoTime() - sendTime);
                        recorder.recordValue(latencyMicros);
                        cumulativeRecorder.recordValue(latencyMicros);

                        semaphore.release();
                    }

                    @Override
                    public void addFailed(ManagedLedgerException exception, Object ctx) {
                        log.warn("Write error on message", exception);
                        System.exit(-1);
                    }
                };

                // Send messages on all topics/producers
                long totalSent = 0;
                while (true) {
                    for (int j = 0; j < nunManagedLedgersForThisThread; j++) {
                        if (arguments.testTime > 0) {
                            if (System.currentTimeMillis() - startTime > arguments.testTime) {
                                log.info("------------------- DONE -----------------------");
                                printAggregatedStats();
                                isDone.set(true);
                                Thread.sleep(5000);
                                System.exit(0);
                            }
                        }

                        if (numMessagesForThisThread > 0) {
                            if (totalSent++ >= numMessagesForThisThread) {
                                log.info("------------------- DONE -----------------------");
                                printAggregatedStats();
                                isDone.set(true);
                                Thread.sleep(5000);
                                System.exit(0);
                            }
                        }

                        semaphore.acquire();
                        rateLimiter.acquire();

                        final long sendTime = System.nanoTime();
                        managedLedgersForThisThread.get(j).asyncAddEntry(payloadBuffer, addEntryCallback,
                                sendTime);
                    }
                }
            } catch (Throwable t) {
                log.error("Got error", t);
            }
        });
    }

    // Print report stats
    long oldTime = System.nanoTime();

    Histogram reportHistogram = null;

    while (true) {
        try {
            Thread.sleep(10000);
        } catch (InterruptedException e) {
            break;
        }

        if (isDone.get()) {
            break;
        }

        long now = System.nanoTime();
        double elapsed = (now - oldTime) / 1e9;

        double rate = messagesSent.sumThenReset() / elapsed;
        double throughput = bytesSent.sumThenReset() / elapsed / 1024 / 1024 * 8;

        reportHistogram = recorder.getIntervalHistogram(reportHistogram);

        log.info(
                "Throughput produced: {}  msg/s --- {} Mbit/s --- Latency: mean: {} ms - med: {} - 95pct: {} - 99pct: {} - 99.9pct: {} - 99.99pct: {} - Max: {}",
                throughputFormat.format(rate), throughputFormat.format(throughput),
                dec.format(reportHistogram.getMean() / 1000.0),
                dec.format(reportHistogram.getValueAtPercentile(50) / 1000.0),
                dec.format(reportHistogram.getValueAtPercentile(95) / 1000.0),
                dec.format(reportHistogram.getValueAtPercentile(99) / 1000.0),
                dec.format(reportHistogram.getValueAtPercentile(99.9) / 1000.0),
                dec.format(reportHistogram.getValueAtPercentile(99.99) / 1000.0),
                dec.format(reportHistogram.getMaxValue() / 1000.0));

        reportHistogram.reset();

        oldTime = now;
    }

    factory.shutdown();
}

From source file:Main.java

private static void throwExceptionIfInterruptedOrCancelled(AtomicBoolean isCanceled)
        throws InterruptedException {
    if (Thread.interrupted() || (isCanceled != null && isCanceled.get())) {
        throw new InterruptedException();
    }// ww  w .java 2s  . c o m
}

From source file:com.addthis.hydra.kafka.consumer.KafkaSource.java

static <E> void putWhileRunning(BlockingQueue<E> queue, E value, AtomicBoolean running) {
    boolean offered = false;
    while (!offered) {
        if (!running.get()) {
            throw BenignKafkaException.INSTANCE;
        }/*w w w .  j  a v a  2s.c o  m*/
        try {
            offered = queue.offer(value, 1, TimeUnit.SECONDS);
        } catch (InterruptedException e) {
            // ignored
        }
    }
}

From source file:Main.java

/**
 * sleep specified time with stop flag./* w  w w .j a  v a  2  s  . c  om*/
 * <p>
 * When flag turns to true, this method should immediately return.
 * </p>
 *
 * @param sleepTime sleep time in milliseconds
 * @param stopFlag  stop flag, if the value is true, end sleep
 * @return true if really sleep enough time, false if thread is interrupted
 */
public static boolean sleep(long sleepTime, AtomicBoolean stopFlag) {
    checkNotNull(stopFlag);
    final long smallTime = 10;
    final long expectedEndTimestamp = System.currentTimeMillis() + sleepTime;

    while (true) {
        long leftTime = expectedEndTimestamp - System.currentTimeMillis();
        if (leftTime <= 0) {
            break;
        }
        if (stopFlag.get() || !sleep(getSmall(leftTime, smallTime))) {
            return false;
        }
    }
    return true;
}

From source file:kn.uni.gis.foxhunt.context.GameContext.java

public static boolean isGameActive() {
    final AtomicBoolean bool = new AtomicBoolean(false);
    HttpContext.getInstance().get(currentGame.getGameUrl().toString(), new EntityHandlerAdapter() {
        @Override//from  w  w  w  .  ja v  a 2s. c o m
        public void handleEntity(HttpEntity entity, int statusCode) {
            bool.set(statusCode == HttpStatus.SC_OK);
        }
    });

    return bool.get();
}

From source file:com.opinionlab.woa.WallOfAwesome.java

private static Handler<RoutingContext> makeDownloadRoute() {
    return routingContext -> EXECUTOR.execute(() -> {
        try {//from  w  ww.j  a v  a2 s. co  m
            final HttpServerResponse response = routingContext.response();
            final AtomicBoolean first = new AtomicBoolean(true);
            response.putHeader("Content-Type", "text/plain");
            response.putHeader("Content-Disposition", "inline;filename=awesome.txt");

            response.setChunked(true);
            response.write("BEGIN AWESOME\n\n");
            AwesomeImap.fetchAwesome().forEach(awesome -> {
                if (!first.get()) {
                    response.write("\n\n---\n\n");
                } else {
                    first.set(false);
                }

                response.write(new ST(AWESOME_TEMPLATE).add("awesome", awesome).render());
            });
            response.write("\n\nEND AWESOME");
            response.end();
        } catch (Throwable t) {
            LOGGER.error("Unable to fetch messages.", t);
        }
    });
}

From source file:com.tc.process.Exec.java

@SuppressWarnings("resource")
public static Result execute(final Process process, String cmd[], String outputLog, byte[] input,
        File workingDir, final long timeout) throws Exception {
    final AtomicBoolean processFinished = new AtomicBoolean();
    if (timeout > 0) {
        Thread timeoutThread = new Thread() {
            @Override//  w  w  w  .j a v a2  s . c  o m
            public void run() {
                ThreadUtil.reallySleep(timeout);
                if (!processFinished.get()) {
                    process.destroy();
                }
            }
        };
        timeoutThread.start();
    }

    Thread inputThread = new InputPumper(input == null ? new byte[] {} : input, process.getOutputStream());

    StreamCollector stderr = null;
    StreamCollector stdout = null;

    FileOutputStream fileOutput = null;
    StreamAppender outputLogger = null;

    String errString = null;
    String outString = null;

    try {
        if (outputLog != null) {
            errString = "stderr output redirected to file " + outputLog;
            outString = "stdout output redirected to file " + outputLog;
            fileOutput = new FileOutputStream(outputLog);
            outputLogger = new StreamAppender(fileOutput);
            outputLogger.writeInput(process.getErrorStream(), process.getInputStream());
        } else {
            stderr = new StreamCollector(process.getErrorStream());
            stdout = new StreamCollector(process.getInputStream());
            stderr.start();
            stdout.start();
        }

        inputThread.start();

        final int exitCode = process.waitFor();
        processFinished.set(true);

        inputThread.join();

        if (outputLogger != null) {
            outputLogger.finish();
        }

        if (stderr != null) {
            stderr.join();
            errString = stderr.toString();
        }

        if (stdout != null) {
            stdout.join();
            outString = stdout.toString();
        }

        return new Result(cmd, outString, errString, exitCode);
    } finally {
        closeQuietly(fileOutput);
    }
}

From source file:com.offbynull.portmapper.common.ProcessUtils.java

/**
 * Run a process and dump the stdout stream to a string.
 * @param timeout maximum amount of time the process can take to run
 * @param command command/*from  w w  w  .  java 2s  .co  m*/
 * @param args arguments
 * @return stdout from the process dumped to a string
 * @throws IOException if the process encounters an error
 * @throws NullPointerException if any arguments are {@code null} or contains {@code null}
 * @throws IllegalArgumentException any numeric argument is negative
 */
public static String runProcessAndDumpOutput(long timeout, String command, String... args) throws IOException {
    Validate.notNull(command);
    Validate.noNullElements(args);
    Validate.inclusiveBetween(0L, Long.MAX_VALUE, timeout);

    String[] pbCmd = new String[args.length + 1];
    pbCmd[0] = command;
    System.arraycopy(args, 0, pbCmd, 1, args.length);

    ProcessBuilder builder = new ProcessBuilder(pbCmd);

    final AtomicBoolean failedFlag = new AtomicBoolean();

    Timer timer = new Timer("Process timeout timer", true);
    Process proc = null;
    try {
        proc = builder.start();

        final Process finalProc = proc;
        timer.schedule(new TimerTask() {

            @Override
            public void run() {
                failedFlag.set(true);
                finalProc.destroy();
            }
        }, timeout);

        String ret = IOUtils.toString(proc.getInputStream());
        if (failedFlag.get()) {
            throw new IOException("Process failed");
        }

        return ret;
    } finally {
        if (proc != null) {
            proc.destroy();
        }
        timer.cancel();
        timer.purge();
    }
}

From source file:CB_Utils.http.HttpUtils.java

/**
 * Executes a HTTP request and returns the response as a string. As a HttpRequestBase is given, a HttpGet or HttpPost be passed for
 * execution.<br>/*from   w  w  w .  j a  v  a2s .c  om*/
 * <br>
 * Over the ICancel interface cycle is queried in 200 mSec, if the download should be canceled!<br>
 * Can be NULL
 * 
 * @param httprequest
 *            HttpRequestBase
 * @param icancel
 *            ICancel interface (maybe NULL)
 * @return
 * @throws IOException
 * @throws ClientProtocolException
 * @throws ConnectTimeoutException
 */
public static String Execute(final HttpRequestBase httprequest, final ICancel icancel)
        throws IOException, ClientProtocolException, ConnectTimeoutException {

    httprequest.setHeader("Accept", "application/json");
    httprequest.setHeader("Content-type", "application/json");

    // Execute HTTP Post Request
    String result = "";

    HttpParams httpParameters = new BasicHttpParams();
    // Set the timeout in milliseconds until a connection is established.
    // The default value is zero, that means the timeout is not used.

    HttpConnectionParams.setConnectionTimeout(httpParameters, conectionTimeout);
    // Set the default socket timeout (SO_TIMEOUT)
    // in milliseconds which is the timeout for waiting for data.

    HttpConnectionParams.setSoTimeout(httpParameters, socketTimeout);

    DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);

    final AtomicBoolean ready = new AtomicBoolean(false);
    if (icancel != null) {
        Thread cancelChekThread = new Thread(new Runnable() {
            @Override
            public void run() {
                do {
                    try {
                        Thread.sleep(200);
                    } catch (InterruptedException e) {
                    }
                    if (icancel.cancel())
                        httprequest.abort();
                } while (!ready.get());
            }
        });
        cancelChekThread.start();// start abort chk thread
    }
    HttpResponse response = httpClient.execute(httprequest);
    ready.set(true);// cancel abort chk thread

    BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
    String line = "";
    while ((line = rd.readLine()) != null) {
        if (Plattform.used == Plattform.Server)
            line = new String(line.getBytes("ISO-8859-1"), "UTF-8");
        result += line + "\n";
    }
    return result;
}

From source file:org.apache.hadoop.hbase.client.TestZKAsyncRegistry.java

static void waitUntilAllReplicasHavingRegionLocation(TableName tbl) throws IOException {
    TEST_UTIL.waitFor(TEST_UTIL.getConfiguration().getLong("hbase.client.sync.wait.timeout.msec", 60000), 200,
            true, new ExplainingPredicate<IOException>() {
                @Override/*from w w  w  .j  a va 2s  .  c  o m*/
                public String explainFailure() throws IOException {
                    return TEST_UTIL.explainTableAvailability(tbl);
                }

                @Override
                public boolean evaluate() throws IOException {
                    AtomicBoolean ready = new AtomicBoolean(true);
                    try {
                        RegionLocations locs = REGISTRY.getMetaRegionLocation().get();
                        assertEquals(3, locs.getRegionLocations().length);
                        IntStream.range(0, 3).forEach(i -> {
                            HRegionLocation loc = locs.getRegionLocation(i);
                            if (loc == null) {
                                ready.set(false);
                            }
                        });
                    } catch (Exception e) {
                        ready.set(false);
                    }
                    return ready.get();
                }
            });
}