Example usage for java.util.concurrent.atomic AtomicInteger set

List of usage examples for java.util.concurrent.atomic AtomicInteger set

Introduction

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

Prototype

public final void set(int newValue) 

Source Link

Document

Sets the value to newValue , with memory effects as specified by VarHandle#setVolatile .

Usage

From source file:Main.java

public static void main(String[] argv) throws Exception {
    AtomicInteger atomicInteger = new AtomicInteger();

    atomicInteger.set(2);

    System.out.println(atomicInteger.longValue());
}

From source file:Main.java

public static void main(String[] argv) throws Exception {
    AtomicInteger atomicInteger = new AtomicInteger();

    atomicInteger.set(2);

    System.out.println(atomicInteger);
}

From source file:org.apache.bookkeeper.benchmark.BenchReadThroughputLatency.java

@SuppressWarnings("deprecation")
public static void main(String[] args) throws Exception {
    Options options = new Options();
    options.addOption("ledger", true, "Ledger to read. If empty, read all ledgers which come available. "
            + " Cannot be used with -listen");
    options.addOption("listen", true, "Listen for creation of <arg> ledgers, and read each one fully");
    options.addOption("password", true, "Password used to access ledgers (default 'benchPasswd')");
    options.addOption("zookeeper", true, "Zookeeper ensemble, default \"localhost:2181\"");
    options.addOption("sockettimeout", true, "Socket timeout for bookkeeper client. In seconds. Default 5");
    options.addOption("help", false, "This message");

    CommandLineParser parser = new PosixParser();
    CommandLine cmd = parser.parse(options, args);

    if (cmd.hasOption("help")) {
        usage(options);/* w  ww  .  ja va2  s.  c  o  m*/
        System.exit(-1);
    }

    final String servers = cmd.getOptionValue("zookeeper", "localhost:2181");
    final byte[] passwd = cmd.getOptionValue("password", "benchPasswd").getBytes(UTF_8);
    final int sockTimeout = Integer.parseInt(cmd.getOptionValue("sockettimeout", "5"));
    if (cmd.hasOption("ledger") && cmd.hasOption("listen")) {
        LOG.error("Cannot used -ledger and -listen together");
        usage(options);
        System.exit(-1);
    }

    final AtomicInteger ledger = new AtomicInteger(0);
    final AtomicInteger numLedgers = new AtomicInteger(0);
    if (cmd.hasOption("ledger")) {
        ledger.set(Integer.parseInt(cmd.getOptionValue("ledger")));
    } else if (cmd.hasOption("listen")) {
        numLedgers.set(Integer.parseInt(cmd.getOptionValue("listen")));
    } else {
        LOG.error("You must use -ledger or -listen");
        usage(options);
        System.exit(-1);
    }

    final CountDownLatch shutdownLatch = new CountDownLatch(1);
    final CountDownLatch connectedLatch = new CountDownLatch(1);
    final String nodepath = String.format("/ledgers/L%010d", ledger.get());

    final ClientConfiguration conf = new ClientConfiguration();
    conf.setReadTimeout(sockTimeout).setZkServers(servers);

    final ZooKeeper zk = new ZooKeeper(servers, 3000, new Watcher() {
        public void process(WatchedEvent event) {
            if (event.getState() == Event.KeeperState.SyncConnected
                    && event.getType() == Event.EventType.None) {
                connectedLatch.countDown();
            }
        }
    });
    final Set<String> processedLedgers = new HashSet<String>();
    try {
        zk.register(new Watcher() {
            public void process(WatchedEvent event) {
                try {
                    if (event.getState() == Event.KeeperState.SyncConnected
                            && event.getType() == Event.EventType.None) {
                        connectedLatch.countDown();
                    } else if (event.getType() == Event.EventType.NodeCreated
                            && event.getPath().equals(nodepath)) {
                        readLedger(conf, ledger.get(), passwd);
                        shutdownLatch.countDown();
                    } else if (event.getType() == Event.EventType.NodeChildrenChanged) {
                        if (numLedgers.get() < 0) {
                            return;
                        }
                        List<String> children = zk.getChildren("/ledgers", true);
                        List<String> ledgers = new ArrayList<String>();
                        for (String child : children) {
                            if (LEDGER_PATTERN.matcher(child).find()) {
                                ledgers.add(child);
                            }
                        }
                        for (String ledger : ledgers) {
                            synchronized (processedLedgers) {
                                if (processedLedgers.contains(ledger)) {
                                    continue;
                                }
                                final Matcher m = LEDGER_PATTERN.matcher(ledger);
                                if (m.find()) {
                                    int ledgersLeft = numLedgers.decrementAndGet();
                                    final Long ledgerId = Long.valueOf(m.group(1));
                                    processedLedgers.add(ledger);
                                    Thread t = new Thread() {
                                        public void run() {
                                            readLedger(conf, ledgerId, passwd);
                                        }
                                    };
                                    t.start();
                                    if (ledgersLeft <= 0) {
                                        shutdownLatch.countDown();
                                    }
                                } else {
                                    LOG.error("Cant file ledger id in {}", ledger);
                                }
                            }
                        }
                    } else {
                        LOG.warn("Unknown event {}", event);
                    }
                } catch (Exception e) {
                    LOG.error("Exception in watcher", e);
                }
            }
        });
        connectedLatch.await();
        if (ledger.get() != 0) {
            if (zk.exists(nodepath, true) != null) {
                readLedger(conf, ledger.get(), passwd);
                shutdownLatch.countDown();
            } else {
                LOG.info("Watching for creation of" + nodepath);
            }
        } else {
            zk.getChildren("/ledgers", true);
        }
        shutdownLatch.await();
        LOG.info("Shutting down");
    } finally {
        zk.close();
    }
}

From source file:com.github.ambry.store.DiskReformatter.java

public static void main(String[] args) throws Exception {
    VerifiableProperties properties = ToolUtils.getVerifiableProperties(args);
    DiskReformatterConfig config = new DiskReformatterConfig(properties);
    StoreConfig storeConfig = new StoreConfig(properties);
    ClusterMapConfig clusterMapConfig = new ClusterMapConfig(properties);
    ServerConfig serverConfig = new ServerConfig(properties);
    ClusterAgentsFactory clusterAgentsFactory = Utils.getObj(clusterMapConfig.clusterMapClusterAgentsFactory,
            clusterMapConfig, config.hardwareLayoutFilePath, config.partitionLayoutFilePath);
    try (ClusterMap clusterMap = clusterAgentsFactory.getClusterMap()) {
        StoreKeyConverterFactory storeKeyConverterFactory = Utils.getObj(
                serverConfig.serverStoreKeyConverterFactory, properties, clusterMap.getMetricRegistry());
        StoreKeyFactory storeKeyFactory = Utils.getObj(storeConfig.storeKeyFactory, clusterMap);
        DataNodeId dataNodeId = clusterMap.getDataNodeId(config.datanodeHostname, config.datanodePort);
        if (dataNodeId == null) {
            throw new IllegalArgumentException("Did not find node in clustermap with hostname:port - "
                    + config.datanodeHostname + ":" + config.datanodePort);
        }//from ww  w .  j  av a 2  s. c  o  m
        DiskReformatter reformatter = new DiskReformatter(dataNodeId, Collections.EMPTY_LIST,
                config.fetchSizeInBytes, storeConfig, storeKeyFactory, clusterMap, SystemTime.getInstance(),
                storeKeyConverterFactory.getStoreKeyConverter());
        AtomicInteger exitStatus = new AtomicInteger(0);
        CountDownLatch latch = new CountDownLatch(config.diskMountPaths.length);
        for (int i = 0; i < config.diskMountPaths.length; i++) {
            int finalI = i;
            Runnable runnable = () -> {
                try {
                    reformatter.reformat(config.diskMountPaths[finalI], new File(config.scratchPaths[finalI]));
                    latch.countDown();
                } catch (Exception e) {
                    throw new IllegalStateException(e);
                }
            };
            Thread thread = Utils.newThread(config.diskMountPaths[finalI] + "-reformatter", runnable, true);
            thread.setUncaughtExceptionHandler((t, e) -> {
                exitStatus.set(1);
                logger.error("Reformatting {} failed", config.diskMountPaths[finalI], e);
                latch.countDown();
            });
            thread.start();
        }
        latch.await();
        System.exit(exitStatus.get());
    }
}

From source file:com.linkedin.pinot.perf.FilterOperatorBenchmark.java

public static void main(String[] args) throws Exception {
    String rootDir = args[0];/*from w  w w  .  ja  va2s.c o m*/
    File[] segmentDirs = new File(rootDir).listFiles();
    String query = args[1];
    AtomicInteger totalDocsMatched = new AtomicInteger(0);
    Pql2Compiler pql2Compiler = new Pql2Compiler();
    BrokerRequest brokerRequest = pql2Compiler.compileToBrokerRequest(query);
    List<Callable<Void>> segmentProcessors = new ArrayList<>();
    long[] timesSpent = new long[segmentDirs.length];
    for (int i = 0; i < segmentDirs.length; i++) {
        File indexSegmentDir = segmentDirs[i];
        System.out.println("Loading " + indexSegmentDir.getName());
        Configuration tableDataManagerConfig = new PropertiesConfiguration();
        List<String> invertedColumns = new ArrayList<>();
        FilenameFilter filter = new FilenameFilter() {

            @Override
            public boolean accept(File dir, String name) {
                return name.endsWith(".bitmap.inv");
            }
        };
        String[] indexFiles = indexSegmentDir.list(filter);
        for (String indexFileName : indexFiles) {
            invertedColumns.add(indexFileName.replace(".bitmap.inv", ""));
        }
        tableDataManagerConfig.setProperty(IndexLoadingConfigMetadata.KEY_OF_LOADING_INVERTED_INDEX,
                invertedColumns);
        IndexLoadingConfigMetadata indexLoadingConfigMetadata = new IndexLoadingConfigMetadata(
                tableDataManagerConfig);
        IndexSegmentImpl indexSegmentImpl = (IndexSegmentImpl) Loaders.IndexSegment.load(indexSegmentDir,
                ReadMode.heap, indexLoadingConfigMetadata);
        segmentProcessors
                .add(new SegmentProcessor(i, indexSegmentImpl, brokerRequest, totalDocsMatched, timesSpent));
    }
    ExecutorService executorService = Executors.newCachedThreadPool();
    for (int run = 0; run < 5; run++) {
        System.out.println("START RUN:" + run);
        totalDocsMatched.set(0);
        long start = System.currentTimeMillis();
        List<Future<Void>> futures = executorService.invokeAll(segmentProcessors);
        for (int i = 0; i < futures.size(); i++) {
            futures.get(i).get();
        }
        long end = System.currentTimeMillis();
        System.out.println("Total docs matched:" + totalDocsMatched + " took:" + (end - start));
        System.out.println("Times spent:" + Arrays.toString(timesSpent));
        System.out.println("END RUN:" + run);
    }
    System.exit(0);
}

From source file:com.raphfrk.craftproxyclient.gui.GUIManager.java

public static JSONObject getPreviousLoginDetails() {
    JSONObject loginInfo = AuthManager.refreshAccessToken();
    if (loginInfo == null) {
        return null;
    }//from  w  w w .j av  a2s .  co  m
    final AtomicInteger option = new AtomicInteger();
    Runnable r = new Runnable() {
        public void run() {
            option.set(JOptionPane.showConfirmDialog(CraftProxyClient.getGUI(),
                    "Login as " + AuthManager.getUsername() + "?", "Login", JOptionPane.YES_NO_OPTION));
        }
    };

    if (SwingUtilities.isEventDispatchThread()) {
        r.run();
    } else {
        try {
            SwingUtilities.invokeAndWait(r);
        } catch (InvocationTargetException | InterruptedException e) {
            return null;
        }
    }
    if (option.get() == 0) {
        return loginInfo;
    } else {
        return null;
    }
}

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

private static void makeAlignGroup() {
    Group alignGroup = new Group(shell, SWT.None);
    alignGroup.setLayout(new RowLayout());
    alignGroup.setText("Alignment group");

    final AtomicInteger prevDir = new AtomicInteger(0);
    final Button alignmentButton = new Button(alignGroup, SWT.ARROW | SWT.UP);
    alignmentButton.addListener(SWT.MouseDown, event -> {
        switch (prevDir.get()) {
        case 0:/*from  w  w  w.j av  a  2  s.c om*/
            alignmentButton.setAlignment(SWT.RIGHT);
            prevDir.set(1);
            break;
        case 1:
            alignmentButton.setAlignment(SWT.DOWN);
            prevDir.set(2);
            break;
        case 2:
            alignmentButton.setAlignment(SWT.LEFT);
            prevDir.set(3);
            break;
        case 3:
            alignmentButton.setAlignment(SWT.UP);
            prevDir.set(0);
        default:
            break;
        }
    });
}

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

private static void makeOrientationGroup() {
    Group orientationGroup = new Group(shell, SWT.None);
    orientationGroup.setLayout(new RowLayout());
    orientationGroup.setText("Orientation group");

    final AtomicInteger prevDir = new AtomicInteger(0);
    final Button alignmentButton = new Button(orientationGroup, SWT.ARROW | SWT.RIGHT);
    alignmentButton.addListener(SWT.MouseDown, event -> {
        switch (prevDir.get()) {
        case 0://from   ww  w.  ja v a2 s .co  m
            alignmentButton.setOrientation(SWT.LEFT_TO_RIGHT);
            prevDir.set(1);
            break;
        case 1:
            alignmentButton.setOrientation(SWT.RIGHT_TO_LEFT);
            prevDir.set(0);
            break;
        default:
            break;
        }
    });
}

From source file:org.polymap.core.operation.OperationWizard.java

/**
 * Creastes and opens a new dialog for the given wizard.
 * <p/>//w  w w.  j av  a  2s .  c o m
 * This method blocks until the wizard dialogs OK button is pressed ot dialog
 * is canceled.
 *
 * @param wizard
 * @return True if the OK button of the wizard was pressed.
 */
public static boolean openDialog(final OperationWizard wizard) {
    final AtomicInteger returnCode = new AtomicInteger(-1);

    wizard.getDisplay().asyncExec(new Runnable() {

        public void run() {
            Shell shell = PolymapWorkbench.getShellToParentOn();
            OperationWizardDialog dialog = new OperationWizardDialog(shell, wizard) {
                @Override
                protected void setReturnCode(int code) {
                    super.setReturnCode(code);
                    returnCode.set(code);
                }
            };

            // earlyListeners
            for (Iterator<IPageChangedListener> it = wizard.earlyListeners.iterator(); it.hasNext();) {
                dialog.addPageChangedListener(it.next());
                it.remove();
            }
            dialog.setBlockOnOpen(false);
            dialog.open();

            //dialog.setBlockOnOpen( true );
            //returnCode.set( dialog.open() );
        }
    });

    // wait for dialog to close
    synchronized (returnCode) {
        while (returnCode.get() == -1 && !wizard.monitor.isCanceled()) {
            try {
                returnCode.wait(1000);
            } catch (InterruptedException e) {
            }
        }
    }
    return returnCode.get() == Window.OK;
}

From source file:jef.testbase.JefTester.java

private static String[] analyzeEntry(String str, AtomicInteger i) {
    int start = str.indexOf(' ', i.get());
    if (start < 0)
        return null;
    start++;/*from  w ww .  ja v  a2 s .c  o m*/
    int keyEnd = str.indexOf('=', start);
    String key = str.substring(start, keyEnd);
    // 
    int urlstart = keyEnd + 1;
    char quot = str.charAt(urlstart);
    if (quot == '\'' || quot == '"') {
        urlstart++;
    }
    // ?
    int urlend = StringUtils.indexOfAny(str, END_CHARS, urlstart);
    String value = str.substring(urlstart, urlend);
    i.set(urlend + 1);
    return new String[] { key, value };
}