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

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

Introduction

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

Prototype

public final int get() 

Source Link

Document

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

Usage

From source file:Main.java

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

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

From source file:Main.java

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

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

From source file:Main.java

public static void main(String[] argv) throws Exception {
    AtomicInteger atomicInteger = new AtomicInteger();
    atomicInteger.addAndGet(10);/*from   w ww . j  ava  2 s.co  m*/
    System.out.println(atomicInteger.get());
}

From source file:com.fjn.helper.frameworkex.apache.commons.pool.connectionPool.ConnectionManager.java

public static void main(String[] args) {
    final ConnectionManager mgr = new ConnectionManager();
    mgr.connFactory = new ConnectionFactory();
    mgr.connFactory.setDriverClass("com.mysql.jdbc.Driver");
    mgr.connFactory.setPassword("mysql");
    mgr.connFactory.setUsername("mysql");
    mgr.connFactory.setUrl("url:localhost:3306"); // ?URL

    mgr.initConnectionPool(1000, 50, 5, 1000 * 60);
    mgr.pool = mgr.connPoolFactory.createPool();

    final AtomicInteger count = new AtomicInteger(0);

    int threadNum = Runtime.getRuntime().availableProcessors();
    ExecutorService client = Executors.newFixedThreadPool(threadNum);
    for (int i = 0; i < threadNum; i++) {
        client.submit(new Runnable() {
            @Override/*from  www .j  a  v  a  2s  .co m*/
            public void run() {
                while (true && count.get() < 100) {
                    try {
                        Thread.sleep(500);
                    } catch (InterruptedException e1) {
                        e1.printStackTrace();
                    }
                    Connection connection = null;

                    try {
                        connection = (Connection) mgr.pool.borrowObject();
                        try {

                            int value = count.incrementAndGet();
                            if (value < 100) {
                                String threadName = Thread.currentThread().getName();

                                int activeNum = mgr.pool.getNumActive();
                                int idleNum = mgr.pool.getNumIdle();
                                String content = "ThreadName: " + threadName + "\t SQL: "
                                        + "insert into tableA ( ct ) values ('" + value + "'); \t activeNum="
                                        + activeNum + "\t idleNum=" + idleNum;
                                System.out.println(content);
                            }

                        } catch (Exception e) {
                            mgr.pool.invalidateObject(connection);
                            connection = null;
                        } finally {
                            // make sure the object is returned to the pool
                            if (null != connection) {
                                mgr.pool.returnObject(connection);
                            }
                        }
                    } catch (Exception e) {
                        // failed to borrow an object
                    }

                }
            }
        });
    }
}

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);// ww w .j a  va 2 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.weibo.motan.demo.client.DemoRpcClient.java

public static void main(String[] args) throws Exception {
    final DescriptiveStatistics stats = new SynchronizedDescriptiveStatistics();

    int threads = Integer.parseInt(args[0]);

    DubboBenchmark.BenchmarkMessage msg = prepareArgs();
    final byte[] msgBytes = msg.toByteArray();

    int n = 1000000;
    final CountDownLatch latch = new CountDownLatch(n);

    ExecutorService es = Executors.newFixedThreadPool(threads);

    final AtomicInteger trans = new AtomicInteger(0);
    final AtomicInteger transOK = new AtomicInteger(0);

    ApplicationContext ctx = new ClassPathXmlApplicationContext(
            new String[] { "classpath:motan_demo_client.xml" });

    MotanDemoService service = (MotanDemoService) ctx.getBean("motanDemoReferer");

    long start = System.currentTimeMillis();
    for (int i = 0; i < n; i++) {
        es.submit(() -> {//from   www  .  j a va  2  s  .c  o  m
            try {

                long t = System.currentTimeMillis();
                DubboBenchmark.BenchmarkMessage m = testSay(service, msgBytes);
                t = System.currentTimeMillis() - t;
                stats.addValue(t);

                trans.incrementAndGet();

                if (m != null && m.getField1().equals("OK")) {
                    transOK.incrementAndGet();
                }

            } finally {
                latch.countDown();
            }
        });
    }

    latch.await();

    start = System.currentTimeMillis() - start;

    System.out.printf("sent     requests    : %d\n", n);
    System.out.printf("received requests    : %d\n", trans.get());
    System.out.printf("received requests_OK : %d\n", transOK.get());
    System.out.printf("throughput  (TPS)    : %d\n", n * 1000 / start);

    System.out.printf("mean: %f\n", stats.getMean());
    System.out.printf("median: %f\n", stats.getPercentile(50));
    System.out.printf("max: %f\n", stats.getMax());
    System.out.printf("min: %f\n", stats.getMin());

    System.out.printf("99P: %f\n", stats.getPercentile(90));

}

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   w  w  w .  j  a  va2 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:edu.msu.cme.rdp.kmer.cli.KmerCoverage.java

/**
 * This program maps the kmers from reads to kmers on each contig,
 * writes the mean, median coverage of each contig to a file
 * writes the kmer abundance to a file//from  w  w  w .  j a va  2  s .  c  o  m
 * @param args
 * @throws IOException 
 */
public static void main(String[] args) throws IOException, InterruptedException {
    int kmerSize = 45;
    final int maxThreads;
    final int maxTasks = 1000;
    final PrintStream match_reads_out;
    try {
        CommandLine cmdLine = new PosixParser().parse(options, args);
        args = cmdLine.getArgs();
        if (args.length < 5) {
            throw new Exception("Unexpected number of arguments");
        }
        kmerSize = Integer.parseInt(args[0]);
        if (kmerSize > Kmer.max_nucl_kmer_size) {
            throw new Exception("kmerSize should be less than " + Kmer.max_nucl_kmer_size);
        }
        if (cmdLine.hasOption("match_reads_out")) {
            match_reads_out = new PrintStream(cmdLine.getOptionValue("match_reads_out"));
        } else {
            match_reads_out = null;
        }
        if (cmdLine.hasOption("threads")) {
            maxThreads = Integer.valueOf(cmdLine.getOptionValue("threads"));
            if (maxThreads >= Runtime.getRuntime().availableProcessors()) {
                System.err.println(" Runtime.getRuntime().availableProcessors() "
                        + Runtime.getRuntime().availableProcessors());
            }

        } else {
            maxThreads = 1;
        }

        final KmerCoverage kmerCoverage = new KmerCoverage(kmerSize, new SequenceReader(new File(args[1])));

        final AtomicInteger outstandingTasks = new AtomicInteger();
        ExecutorService service = Executors.newFixedThreadPool(maxThreads);

        Sequence seq;

        // parse one file at a time
        for (int index = 4; index < args.length; index++) {

            SequenceReader reader = new SequenceReader(new File(args[index]));
            while ((seq = reader.readNextSequence()) != null) {
                if (seq.getSeqString().length() < kmerSize) {
                    continue;
                }
                final Sequence threadSeq = seq;

                Runnable r = new Runnable() {

                    public void run() {
                        try {
                            kmerCoverage.processReads(threadSeq, match_reads_out);
                            outstandingTasks.decrementAndGet();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                };

                outstandingTasks.incrementAndGet();
                service.submit(r);

                while (outstandingTasks.get() >= maxTasks)
                    ;

            }
            reader.close();
        }
        service.shutdown();
        service.awaitTermination(1, TimeUnit.DAYS);

        kmerCoverage.printCovereage(new FileOutputStream(new File(args[2])),
                new FileOutputStream(new File(args[3])));
        if (match_reads_out != null) {
            match_reads_out.close();
        }
    } catch (Exception e) {
        new HelpFormatter().printHelp(
                "KmerCoverage <kmerSize> <query_file> <coverage_out> <abundance_out> <reads_file> <reads_file>...\nmaximum kmerSize "
                        + Kmer.max_nucl_kmer_size,
                options);
        e.printStackTrace();
        System.exit(1);
    }
}

From source file:PinotThroughput.java

@SuppressWarnings("InfiniteLoopStatement")
public static void main(String[] args) throws Exception {
    final int numQueries = QUERIES.length;
    final Random random = new Random(RANDOM_SEED);
    final AtomicInteger counter = new AtomicInteger(0);
    final AtomicLong totalResponseTime = new AtomicLong(0L);
    final ExecutorService executorService = Executors.newFixedThreadPool(NUM_CLIENTS);

    for (int i = 0; i < NUM_CLIENTS; i++) {
        executorService.submit(new Runnable() {
            @Override//from   w w w. j a  va2  s  .  c  om
            public void run() {
                try (CloseableHttpClient client = HttpClients.createDefault()) {
                    HttpPost post = new HttpPost("http://localhost:8099/query");
                    CloseableHttpResponse res;
                    while (true) {
                        String query = QUERIES[random.nextInt(numQueries)];
                        post.setEntity(new StringEntity("{\"pql\":\"" + query + "\"}"));
                        long start = System.currentTimeMillis();
                        res = client.execute(post);
                        res.close();
                        counter.getAndIncrement();
                        totalResponseTime.getAndAdd(System.currentTimeMillis() - start);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    long startTime = System.currentTimeMillis();
    while (true) {
        Thread.sleep(REPORT_INTERVAL_MILLIS);
        double timePassedSeconds = ((double) (System.currentTimeMillis() - startTime)) / MILLIS_PER_SECOND;
        int count = counter.get();
        double avgResponseTime = ((double) totalResponseTime.get()) / count;
        System.out.println("Time Passed: " + timePassedSeconds + "s, Query Executed: " + count + ", QPS: "
                + count / timePassedSeconds + ", Avg Response Time: " + avgResponseTime + "ms");
    }
}

From source file:com.linkedin.pinotdruidbenchmark.PinotThroughput.java

@SuppressWarnings("InfiniteLoopStatement")
public static void main(String[] args) throws Exception {
    if (args.length != 3 && args.length != 4) {
        System.err.println(/*from  w w  w.  j  a va  2s. com*/
                "3 or 4 arguments required: QUERY_DIR, RESOURCE_URL, NUM_CLIENTS, TEST_TIME (seconds).");
        return;
    }

    File queryDir = new File(args[0]);
    String resourceUrl = args[1];
    final int numClients = Integer.parseInt(args[2]);
    final long endTime;
    if (args.length == 3) {
        endTime = Long.MAX_VALUE;
    } else {
        endTime = System.currentTimeMillis() + Integer.parseInt(args[3]) * MILLIS_PER_SECOND;
    }

    File[] queryFiles = queryDir.listFiles();
    assert queryFiles != null;
    Arrays.sort(queryFiles);

    final int numQueries = queryFiles.length;
    final HttpPost[] httpPosts = new HttpPost[numQueries];
    for (int i = 0; i < numQueries; i++) {
        HttpPost httpPost = new HttpPost(resourceUrl);
        String query = new BufferedReader(new FileReader(queryFiles[i])).readLine();
        httpPost.setEntity(new StringEntity("{\"pql\":\"" + query + "\"}"));
        httpPosts[i] = httpPost;
    }

    final AtomicInteger counter = new AtomicInteger(0);
    final AtomicLong totalResponseTime = new AtomicLong(0L);
    final ExecutorService executorService = Executors.newFixedThreadPool(numClients);

    for (int i = 0; i < numClients; i++) {
        executorService.submit(new Runnable() {
            @Override
            public void run() {
                try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
                    while (System.currentTimeMillis() < endTime) {
                        long startTime = System.currentTimeMillis();
                        CloseableHttpResponse httpResponse = httpClient
                                .execute(httpPosts[RANDOM.nextInt(numQueries)]);
                        httpResponse.close();
                        long responseTime = System.currentTimeMillis() - startTime;
                        counter.getAndIncrement();
                        totalResponseTime.getAndAdd(responseTime);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
    }
    executorService.shutdown();

    long startTime = System.currentTimeMillis();
    while (System.currentTimeMillis() < endTime) {
        Thread.sleep(REPORT_INTERVAL_MILLIS);
        double timePassedSeconds = ((double) (System.currentTimeMillis() - startTime)) / MILLIS_PER_SECOND;
        int count = counter.get();
        double avgResponseTime = ((double) totalResponseTime.get()) / count;
        System.out.println("Time Passed: " + timePassedSeconds + "s, Query Executed: " + count + ", QPS: "
                + count / timePassedSeconds + ", Avg Response Time: " + avgResponseTime + "ms");
    }
}