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

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

Introduction

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

Prototype

public AtomicBoolean(boolean initialValue) 

Source Link

Document

Creates a new AtomicBoolean with the given initial value.

Usage

From source file:Main.java

public static void main(String[] argv) throws Exception {
    AtomicBoolean atomicBoolean = new AtomicBoolean(true);

    System.out.println(atomicBoolean);
}

From source file:com.blockhaus2000.csvviewer.CsvViewerMain.java

public static void main(final String[] args) {
    try (final CSVParser parser = new CSVParser(new InputStreamReader(System.in), CSVFormat.DEFAULT)) {
        final Table table = new Table();

        final Map<String, Integer> headerMap = parser.getHeaderMap();
        if (headerMap != null) {
            final TableRow headerRow = new TableRow();
            headerMap.keySet().forEach(headerData -> headerRow.addCell(new TableRowCell(headerData)));
            table.setHeaderRow(headerRow);
        }//from www  .ja v a  2s.c  om

        final AtomicBoolean asHeader = new AtomicBoolean(headerMap == null);
        parser.getRecords().forEach(record -> {
            final TableRow row = new TableRow();
            record.forEach(rowData -> row.addCell(new TableRowCell(rowData)));
            if (asHeader.getAndSet(false)) {
                table.setHeaderRow(row);
            } else {
                table.addRow(row);
            }
        });

        System.out.println(table.getFormattedString());
    } catch (final IOException cause) {
        throw new RuntimeException("An error occurred whilst parsing stdin!", cause);
    }
}

From source file:org.eclipse.swt.snippets.Snippet141.java

public static void main(String[] args) {
    display = new Display();
    shell = new Shell(display);
    shell.setText("Snippet 141");
    shell.setSize(300, 300);/*  ww w. j  a  v  a  2 s.co  m*/
    shell.open();
    shellGC = new GC(shell);
    shellBackground = shell.getBackground();

    FileDialog dialog = new FileDialog(shell);
    dialog.setFilterExtensions(new String[] { "*.gif" });
    String fileName = dialog.open();
    final AtomicBoolean stopAnimation = new AtomicBoolean(false);
    if (fileName != null) {
        loader = new ImageLoader();
        try {
            imageDataArray = loader.load(fileName);
            if (imageDataArray.length > 1) {
                animateThread = new Thread("Animation") {
                    @Override
                    public void run() {
                        /* Create an off-screen image to draw on, and fill it with the shell background. */
                        Image offScreenImage = new Image(display, loader.logicalScreenWidth,
                                loader.logicalScreenHeight);
                        GC offScreenImageGC = new GC(offScreenImage);
                        offScreenImageGC.setBackground(shellBackground);
                        offScreenImageGC.fillRectangle(0, 0, loader.logicalScreenWidth,
                                loader.logicalScreenHeight);

                        try {
                            /* Create the first image and draw it on the off-screen image. */
                            int imageDataIndex = 0;
                            ImageData imageData = imageDataArray[imageDataIndex];
                            if (image != null && !image.isDisposed())
                                image.dispose();
                            image = new Image(display, imageData);
                            offScreenImageGC.drawImage(image, 0, 0, imageData.width, imageData.height,
                                    imageData.x, imageData.y, imageData.width, imageData.height);

                            /* Now loop through the images, creating and drawing each one
                             * on the off-screen image before drawing it on the shell. */
                            int repeatCount = loader.repeatCount;
                            while ((loader.repeatCount == 0 || repeatCount > 0) && !stopAnimation.get()) {
                                switch (imageData.disposalMethod) {
                                case SWT.DM_FILL_BACKGROUND:
                                    /* Fill with the background color before drawing. */
                                    Color bgColor = null;
                                    if (useGIFBackground && loader.backgroundPixel != -1) {
                                        bgColor = new Color(display,
                                                imageData.palette.getRGB(loader.backgroundPixel));
                                    }
                                    offScreenImageGC.setBackground(bgColor != null ? bgColor : shellBackground);
                                    offScreenImageGC.fillRectangle(imageData.x, imageData.y, imageData.width,
                                            imageData.height);
                                    if (bgColor != null)
                                        bgColor.dispose();
                                    break;
                                case SWT.DM_FILL_PREVIOUS:
                                    /* Restore the previous image before drawing. */
                                    offScreenImageGC.drawImage(image, 0, 0, imageData.width, imageData.height,
                                            imageData.x, imageData.y, imageData.width, imageData.height);
                                    break;
                                }

                                imageDataIndex = (imageDataIndex + 1) % imageDataArray.length;
                                imageData = imageDataArray[imageDataIndex];
                                image.dispose();
                                image = new Image(display, imageData);
                                offScreenImageGC.drawImage(image, 0, 0, imageData.width, imageData.height,
                                        imageData.x, imageData.y, imageData.width, imageData.height);

                                /* Draw the off-screen image to the shell. */
                                shellGC.drawImage(offScreenImage, 0, 0);

                                /* Sleep for the specified delay time (adding commonly-used slow-down fudge factors). */
                                try {
                                    int ms = imageData.delayTime * 10;
                                    if (ms < 20)
                                        ms += 30;
                                    if (ms < 30)
                                        ms += 10;
                                    Thread.sleep(ms);
                                } catch (InterruptedException e) {
                                }

                                /* If we have just drawn the last image, decrement the repeat count and start again. */
                                if (imageDataIndex == imageDataArray.length - 1)
                                    repeatCount--;
                            }
                        } catch (SWTException ex) {
                            System.out.println("There was an error animating the GIF");
                        } finally {
                            if (offScreenImage != null && !offScreenImage.isDisposed())
                                offScreenImage.dispose();
                            if (offScreenImageGC != null && !offScreenImageGC.isDisposed())
                                offScreenImageGC.dispose();
                            if (image != null && !image.isDisposed())
                                image.dispose();
                        }
                    }
                };
                animateThread.setDaemon(true);
                animateThread.start();
            }
        } catch (SWTException ex) {
            System.out.println("There was an error loading the GIF");
        }
    }

    while (!shell.isDisposed()) {
        if (!display.readAndDispatch())
            display.sleep();
    }
    stopAnimation.set(true);
    display.dispose();
}

From source file:accumulo.AccumuloStuff.java

public static void main(String[] args) throws Exception {
    File tmp = new File(System.getProperty("user.dir") + "/target/mac-test");
    if (tmp.exists()) {
        FileUtils.deleteDirectory(tmp);/* www .j a v a  2 s . c om*/
    }
    tmp.mkdirs();
    String passwd = "password";

    MiniAccumuloConfigImpl cfg = new MiniAccumuloConfigImpl(tmp, passwd);
    cfg.setNumTservers(1);
    //    cfg.useMiniDFS(true);

    final MiniAccumuloClusterImpl cluster = cfg.build();
    setCoreSite(cluster);
    cluster.start();

    ExecutorService svc = Executors.newFixedThreadPool(2);

    try {
        Connector conn = cluster.getConnector("root", passwd);
        String table = "table";
        conn.tableOperations().create(table);

        final BatchWriter bw = conn.createBatchWriter(table, new BatchWriterConfig());
        final AtomicBoolean flushed = new AtomicBoolean(false);

        Runnable writer = new Runnable() {
            @Override
            public void run() {
                try {
                    Mutation m = new Mutation("row");
                    m.put("colf", "colq", "value");
                    bw.addMutation(m);
                    bw.flush();
                    flushed.set(true);
                } catch (Exception e) {
                    log.error("Got exception trying to flush mutation", e);
                }

                log.info("Exiting batchwriter thread");
            }
        };

        Runnable restarter = new Runnable() {
            @Override
            public void run() {
                try {
                    for (ProcessReference proc : cluster.getProcesses().get(ServerType.TABLET_SERVER)) {
                        cluster.killProcess(ServerType.TABLET_SERVER, proc);
                    }
                    cluster.exec(TabletServer.class);
                } catch (Exception e) {
                    log.error("Caught exception restarting tabletserver", e);
                }
                log.info("Exiting restart thread");
            }
        };

        svc.execute(writer);
        svc.execute(restarter);

        log.info("Waiting for shutdown");
        svc.shutdown();
        if (!svc.awaitTermination(120, TimeUnit.SECONDS)) {
            log.info("Timeout on shutdown exceeded");
            svc.shutdownNow();
        } else {
            log.info("Cleanly shutdown");
            log.info("Threadpool is terminated? " + svc.isTerminated());
        }

        if (flushed.get()) {
            log.info("****** BatchWriter was flushed *********");
        } else {
            log.info("****** BatchWriter was NOT flushed *********");
        }

        bw.close();

        log.info("Got record {}", Iterables.getOnlyElement(conn.createScanner(table, Authorizations.EMPTY)));
    } finally {
        cluster.stop();
    }
}

From source file:com.easarrive.aws.plugins.common.service.impl.SimpleProducerConsumer.java

public static void main(String[] args) throws InterruptedException {
    final AWSCredentials credentials = new BasicAWSCredentials("AKIAIDPJMKK4UHLE3OVA",
            "A+cn+TT3tUs6xbto5k1IKkWwPLBq995aOkqKxZNY");

    final String endpoint = "sqs.us-west-2.amazonaws.com";
    final String queueName = "image";
    final int producerCount = 10;
    final int consumerCount = 3;
    final int batchSize = 3;
    final int messageSizeByte = 10000;
    final int runTimeMinutes = 100;

    // configure the SQS client with enough connections for all producer and
    // consumer threads
    AmazonSQS sqsClient = new AmazonSQSClient(credentials,
            new ClientConfiguration().withMaxConnections(producerCount + consumerCount));
    sqsClient.setEndpoint(endpoint);/*  w  ww  .  java2 s  .  com*/
    String queueUrl = sqsClient.getQueueUrl(new GetQueueUrlRequest(queueName)).getQueueUrl();

    // the flag to stop producer, consumer, and monitor threads
    AtomicBoolean stop = new AtomicBoolean(false);

    // start the producers
    final AtomicInteger producedCount = new AtomicInteger();
    Thread[] producers = new Thread[producerCount];
    for (int i = 0; i < producerCount; i++) {
        producers[i] = new BatchProducer(sqsClient, queueUrl, batchSize, messageSizeByte, producedCount, stop);
        producers[i].start();
    }

    // start the consumers
    final AtomicInteger consumedCount = new AtomicInteger();
    Thread[] consumers = new Thread[consumerCount];
    for (int i = 0; i < consumerCount; i++) {
        consumers[i] = new BatchConsumer(sqsClient, queueUrl, batchSize, consumedCount, stop);
        consumers[i].start();
    }

    // start the monitor (thread)
    Thread monitor = new Monitor(producedCount, consumedCount, stop);
    monitor.start();

    // wait for the specified amount of time then stop
    Thread.sleep(TimeUnit.MINUTES.toMillis(Math.min(runTimeMinutes, MAX_RUNTIME_MINUTES)));
    stop.set(true);

    // join all threads
    for (int i = 0; i < producerCount; i++)
        producers[i].join();

    for (int i = 0; i < consumerCount; i++)
        consumers[i].join();

    monitor.interrupt();
    monitor.join();
}

From source file:com.arpnetworking.tsdaggregator.TsdAggregator.java

/**
 * Entry point for Time Series Data (TSD) Aggregator.
 *
 * @param args the command line arguments
 *//*from  w w w  . j av a2 s  . co m*/
public static void main(final String[] args) {
    LOGGER.info("Launching tsd-aggregator");

    // Global initialization
    Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
        @Override
        public void uncaughtException(final Thread thread, final Throwable throwable) {
            LOGGER.error("Unhandled exception!", throwable);
        }
    });

    Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
        @Override
        public void run() {
            final LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory();
            context.stop();
        }
    }));

    System.setProperty("org.vertx.logger-delegate-factory-class-name",
            "org.vertx.java.core.logging.impl.SLF4JLogDelegateFactory");

    // Run the tsd aggregator
    if (args.length != 1) {
        throw new RuntimeException("No configuration file specified");
    }
    LOGGER.debug(String.format("Loading configuration from file; file=%s", args[0]));

    final File configurationFile = new File(args[0]);
    final Configurator<TsdAggregator, TsdAggregatorConfiguration> configurator = new Configurator<>(
            TsdAggregator.class, TsdAggregatorConfiguration.class);
    final ObjectMapper objectMapper = TsdAggregatorConfiguration.createObjectMapper();
    final DynamicConfiguration configuration = new DynamicConfiguration.Builder().setObjectMapper(objectMapper)
            .addSourceBuilder(
                    new JsonNodeFileSource.Builder().setObjectMapper(objectMapper).setFile(configurationFile))
            .addTrigger(new FileTrigger.Builder().setFile(configurationFile).build()).addListener(configurator)
            .build();

    configuration.launch();

    final AtomicBoolean isRunning = new AtomicBoolean(true);
    Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
        @Override
        public void run() {
            LOGGER.info("Stopping tsd-aggregator");
            configuration.shutdown();
            configurator.shutdown();
            isRunning.set(false);
        }
    }));

    while (isRunning.get()) {
        try {
            Thread.sleep(30000);
        } catch (final InterruptedException e) {
            break;
        }
    }

    LOGGER.info("Exiting tsd-aggregator");
}

From source file:com.mapr.synth.Synth.java

public static void main(String[] args)
        throws IOException, CmdLineException, InterruptedException, ExecutionException {
    final Options opts = new Options();
    CmdLineParser parser = new CmdLineParser(opts);
    try {/*from   ww  w . j  a  v a 2  s  .  c  o  m*/
        parser.parseArgument(args);
    } catch (CmdLineException e) {
        System.err.println("Usage: " + "[ -count <number>G|M|K ] " + "-schema schema-file "
                + "[-quote DOUBLE_QUOTE|BACK_SLASH|OPTIMISTIC] " + "[-format JSON|TSV|CSV|XML ] "
                + "[-threads n] " + "[-output output-directory-name] ");
        throw e;
    }
    Preconditions.checkArgument(opts.threads > 0 && opts.threads <= 2000,
            "Must have at least one thread and no more than 2000");

    if (opts.threads > 1) {
        Preconditions.checkArgument(!"-".equals(opts.output),
                "If more than on thread is used, you have to use -output to set the output directory");
    }

    File outputDir = new File(opts.output);
    if (!"-".equals(opts.output)) {
        if (!outputDir.exists()) {
            Preconditions.checkState(outputDir.mkdirs(),
                    String.format("Couldn't create output directory %s", opts.output));
        }
        Preconditions.checkArgument(outputDir.exists() && outputDir.isDirectory(),
                String.format("Couldn't create directory %s", opts.output));
    }

    if (opts.schema == null) {
        throw new IllegalArgumentException("Must specify schema file using [-schema filename] option");
    }
    final SchemaSampler sampler = new SchemaSampler(opts.schema);
    final AtomicLong rowCount = new AtomicLong();

    final List<ReportingWorker> tasks = Lists.newArrayList();
    int limit = (opts.count + opts.threads - 1) / opts.threads;
    int remaining = opts.count;
    for (int i = 0; i < opts.threads; i++) {

        final int count = Math.min(limit, remaining);
        remaining -= count;

        tasks.add(new ReportingWorker(opts, sampler, rowCount, count, i));
    }

    final double t0 = System.nanoTime() * 1e-9;
    ExecutorService pool = Executors.newFixedThreadPool(opts.threads);
    ScheduledExecutorService blinker = Executors.newScheduledThreadPool(1);
    final AtomicBoolean finalRun = new AtomicBoolean(false);

    final PrintStream sideLog = new PrintStream(new FileOutputStream("side-log"));
    Runnable blink = new Runnable() {
        public double oldT;
        private long oldN;

        @Override
        public void run() {
            double t = System.nanoTime() * 1e-9;
            long n = rowCount.get();
            System.err.printf("%s\t%d\t%.1f\t%d\t%.1f\t%.3f\n", finalRun.get() ? "F" : "R", opts.threads,
                    t - t0, n, n / (t - t0), (n - oldN) / (t - oldT));
            for (ReportingWorker task : tasks) {
                ReportingWorker.ThreadReport r = task.report();
                sideLog.printf("\t%d\t%.2f\t%.2f\t%.2f\t%.1f\t%.1f\n", r.fileNumber, r.threadTime, r.userTime,
                        r.wallTime, r.rows / r.threadTime, r.rows / r.wallTime);
            }
            oldN = n;
            oldT = t;
        }
    };
    if (!"-".equals(opts.output)) {
        blinker.scheduleAtFixedRate(blink, 0, 10, TimeUnit.SECONDS);
    }
    List<Future<Integer>> results = pool.invokeAll(tasks);

    int total = 0;
    for (Future<Integer> result : results) {
        total += result.get();
    }
    Preconditions.checkState(total == opts.count, String
            .format("Expected to generate %d lines of output, but actually generated %d", opts.count, total));
    pool.shutdownNow();
    blinker.shutdownNow();
    finalRun.set(true);
    sideLog.close();
    blink.run();
}

From source file:com.dxc.temp.SimpleProducerConsumer.java

public static void main(String[] args) throws InterruptedException {
    int argIndex = 0;

    final String accessKey = args[argIndex++];
    final String secretKey = args[argIndex++];
    final AWSCredentials credentials = new BasicAWSCredentials(accessKey, secretKey);

    final String endpoint = args[argIndex++];
    final String queueName = args[argIndex++];
    final int producerCount = Integer.parseInt(args[argIndex++]);
    final int consumerCount = Integer.parseInt(args[argIndex++]);
    final int batchSize = Integer.parseInt(args[argIndex++]);
    final int messageSizeByte = Integer.parseInt(args[argIndex++]);
    final int runTimeMinutes = Integer.parseInt(args[argIndex++]);

    // configure the SQS client with enough connections for all producer and
    // consumer threads
    AmazonSQS sqsClient = new AmazonSQSClient(credentials,
            new ClientConfiguration().withMaxConnections(producerCount + consumerCount));
    sqsClient.setEndpoint(endpoint);/*  w  w w.  ja va2s  .  c o  m*/
    String queueUrl = sqsClient.getQueueUrl(new GetQueueUrlRequest(queueName)).getQueueUrl();

    // the flag to stop producer, consumer, and monitor threads
    AtomicBoolean stop = new AtomicBoolean(false);

    // start the producers
    final AtomicInteger producedCount = new AtomicInteger();
    Thread[] producers = new Thread[producerCount];
    for (int i = 0; i < producerCount; i++) {
        if (batchSize == 1)
            producers[i] = new Producer(sqsClient, queueUrl, messageSizeByte, producedCount, stop);
        else
            producers[i] = new BatchProducer(sqsClient, queueUrl, batchSize, messageSizeByte, producedCount,
                    stop);
        producers[i].start();
    }

    // start the consumers
    final AtomicInteger consumedCount = new AtomicInteger();
    Thread[] consumers = new Thread[consumerCount];
    for (int i = 0; i < consumerCount; i++) {
        if (batchSize == 1)
            consumers[i] = new Consumer(sqsClient, queueUrl, consumedCount, stop);
        else
            consumers[i] = new BatchConsumer(sqsClient, queueUrl, batchSize, consumedCount, stop);
        consumers[i].start();
    }

    // start the monitor (thread)
    Thread monitor = new Monitor(producedCount, consumedCount, stop);
    monitor.start();

    // wait for the specified amount of time then stop
    Thread.sleep(TimeUnit.MINUTES.toMillis(Math.min(runTimeMinutes, MAX_RUNTIME_MINUTES)));
    stop.set(true);

    // join all threads
    for (int i = 0; i < producerCount; i++)
        producers[i].join();

    for (int i = 0; i < consumerCount; i++)
        consumers[i].join();

    monitor.interrupt();
    monitor.join();
}

From source file:de.codesourcery.eve.skills.ui.utils.CalendarWidget.java

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

    final SimpleDateFormat DF = new SimpleDateFormat("dd.MM");

    final Calendar specialDate = Calendar.getInstance();
    specialDate.add(Calendar.DAY_OF_MONTH, 5);

    final AtomicBoolean doStuff = new AtomicBoolean(false);

    final ICalendarRenderer renderer = new ICalendarRenderer() {

        @Override/*from w ww . ja  v  a2 s. co  m*/
        public String getDateLabel(Date date) {
            return DF.format(date);
        }

        @Override
        public String getText(Date date) {
            if (DateUtils.isSameDay(date, specialDate.getTime()) && doStuff.get()) {
                return "SPECIAL !!!";
            }
            return "some\nmultiline\ntext";
        }

        @Override
        public String getToolTip(Date date) {
            return getText(date);
        }

        @Override
        public Color getTextColor(Date date) {
            return Color.RED;
        }
    };

    final JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.getContentPane().setLayout(new GridBagLayout());

    final CalendarWidget widget = new CalendarWidget(new Date(), renderer);

    widget.addSelectionListener(new ISelectionListener<Date>() {

        @Override
        public void selectionChanged(Date selected) {
            System.out.println("Selected date > " + selected);
        }
    });
    frame.getContentPane().add(widget, new ConstraintsBuilder().end());
    frame.pack();
    frame.setVisible(true);

    java.lang.Thread.sleep(2 * 1000);
    doStuff.set(true);
    widget.refreshDateLabel(specialDate.getTime());

}

From source file:Main.java

private static synchronized boolean isRunningTest() {
    if (null == isRunningTest) {
        boolean isTest;

        try {/*  ww w  .j  av  a  2 s. c o m*/
            Class.forName("android.support.test.espresso.Espresso");
            isTest = true;
        } catch (ClassNotFoundException e) {
            isTest = false;
        }

        isRunningTest = new AtomicBoolean(isTest);
    }

    return isRunningTest.get();
}