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

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

Introduction

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

Prototype

public final int getAndIncrement() 

Source Link

Document

Atomically increments the current value, with memory effects as specified by VarHandle#getAndAdd .

Usage

From source file:Main.java

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

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

From source file:examples.CheckSessionState.java

public static void main(String[] args) {
    if (args.length == 0) {
        System.err.println("At least one path to serialized session required.");
        System.exit(1);//from ww w  .  j  av a  2s  . c  om
    }
    for (String sessionStatePath : args) {
        try {
            File sessionStateFile = new File(sessionStatePath);
            SessionState sessionState = JACKSON.readValue(sessionStateFile, SessionState.class);
            final AtomicInteger idx = new AtomicInteger(0);
            sessionState.foreachPartition(new Action1<PartitionState>() {
                @Override
                public void call(PartitionState state) {
                    int partition = idx.getAndIncrement();
                    if (lessThan(state.getEndSeqno(), state.getStartSeqno())) {
                        System.out.printf("stream request for partition %d will fail because "
                                + "start sequence number (%d) is larger than " + "end sequence number (%d)\n",
                                partition, state.getStartSeqno(), state.getEndSeqno());
                    }
                    if (lessThan(state.getStartSeqno(), state.getSnapshotStartSeqno())) {
                        System.out.printf(
                                "stream request for partition %d will fail because "
                                        + "snapshot start sequence number (%d) must not be larger than "
                                        + "start sequence number (%d)\n",
                                partition, state.getSnapshotStartSeqno(), state.getStartSeqno());
                    }
                    if (lessThan(state.getSnapshotEndSeqno(), state.getStartSeqno())) {
                        System.out.printf(
                                "stream request for partition %d will fail because "
                                        + "start sequence number (%d) must not be larger than "
                                        + "snapshot end sequence number (%d)\n",
                                partition, state.getStartSeqno(), state.getSnapshotEndSeqno());
                    }
                }
            });
        } catch (IOException e) {
            System.out.println("Failed to decode " + sessionStatePath + ": " + e);
        }
    }
}

From source file:org.gridgain.startup.GridVmNodesStarter.java

/**
 * Main entry point./*from www. j a v a 2  s.co m*/
 *
 * @param args Command line arguments.
 * @throws GridException If failed.
 */
public static void main(String[] args) throws GridException {
    System.setProperty(GG_UPDATE_NOTIFIER, "false");

    Options options = createOptions();

    // Create the command line parser.
    CommandLineParser parser = new PosixParser();

    String cfgPath = null;

    Integer nodesCnt = null;

    try {
        CommandLine cmd = parser.parse(options, args);

        if (cmd.hasOption(OPTION_CFG))
            cfgPath = cmd.getOptionValue(OPTION_CFG);

        if (cmd.hasOption(OPTION_N))
            try {
                nodesCnt = Integer.parseInt(cmd.getOptionValue(OPTION_N));
            } catch (NumberFormatException ignored) {
                // No-op.
            }

        if (nodesCnt == null)
            nodesCnt = DFLT_NODES_COUNT;
    } catch (ParseException e) {
        exit(e.getMessage(), options, -1);
    }

    System.out.println();
    System.out.println(">>> VM Nodes Starter parameters:");
    System.out.println("  Nodes Count: " + nodesCnt);
    System.out.println("  Config Path: " + cfgPath);
    System.out.println();

    final GridConfiguration[] cfgs = new GridConfiguration[nodesCnt];

    for (int i = 0; i < nodesCnt; i++)
        cfgs[i] = getConfigurations(cfgPath).iterator().next();

    final AtomicInteger cfgIdx = new AtomicInteger(0);

    GridTestUtils.runMultiThreadedAsync(new Callable<Object>() {
        @Override
        public Object call() throws Exception {
            G.start(cfgs[cfgIdx.getAndIncrement()]);

            return null;
        }
    }, nodesCnt, "test-node-starter");
}

From source file:org.apache.ignite.startup.GridVmNodesStarter.java

/**
 * Main entry point.//from w  ww .ja  v a 2  s  .  c  o m
 *
 * @param args Command line arguments.
 * @throws IgniteCheckedException If failed.
 */
public static void main(String[] args) throws IgniteCheckedException {
    System.setProperty(IGNITE_UPDATE_NOTIFIER, "false");

    Options options = createOptions();

    // Create the command line parser.
    CommandLineParser parser = new PosixParser();

    String cfgPath = null;

    Integer nodesCnt = null;

    try {
        CommandLine cmd = parser.parse(options, args);

        if (cmd.hasOption(OPTION_CFG))
            cfgPath = cmd.getOptionValue(OPTION_CFG);

        if (cmd.hasOption(OPTION_N))
            try {
                nodesCnt = Integer.parseInt(cmd.getOptionValue(OPTION_N));
            } catch (NumberFormatException ignored) {
                // No-op.
            }

        if (nodesCnt == null)
            nodesCnt = DFLT_NODES_COUNT;
    } catch (ParseException e) {
        exit(e.getMessage(), options, -1);
    }

    System.out.println();
    System.out.println(">>> VM Nodes Starter parameters:");
    System.out.println("  Nodes Count: " + nodesCnt);
    System.out.println("  Config Path: " + cfgPath);
    System.out.println();

    final IgniteConfiguration[] cfgs = new IgniteConfiguration[nodesCnt];

    for (int i = 0; i < nodesCnt; i++)
        cfgs[i] = getConfigurations(cfgPath).iterator().next();

    final AtomicInteger cfgIdx = new AtomicInteger(0);

    GridTestUtils.runMultiThreadedAsync(new Callable<Object>() {
        @Override
        public Object call() throws Exception {
            G.start(cfgs[cfgIdx.getAndIncrement()]);

            return null;
        }
    }, nodesCnt, "test-node-starter");
}

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(/*  www . j ava 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");
    }
}

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 v a 2  s . c o  m*/
            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.DruidThroughput.java

@SuppressWarnings("InfiniteLoopStatement")
public static void main(String[] args) throws Exception {
    if (args.length != 3 && args.length != 4) {
        System.err.println(//w ww .  j av a 2 s  .  c om
                "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);
        httpPost.addHeader("content-type", "application/json");
        StringBuilder stringBuilder = new StringBuilder();
        try (BufferedReader bufferedReader = new BufferedReader(new FileReader(queryFiles[i]))) {
            int length;
            while ((length = bufferedReader.read(CHAR_BUFFER)) > 0) {
                stringBuilder.append(new String(CHAR_BUFFER, 0, length));
            }
        }
        String query = stringBuilder.toString();
        httpPost.setEntity(new StringEntity(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");
    }
}

From source file:DruidThroughput.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/*  ww  w. j  a  va  2s  .co m*/
            public void run() {
                try (CloseableHttpClient client = HttpClients.createDefault()) {
                    HttpPost post = new HttpPost("http://localhost:8082/druid/v2/?pretty");
                    post.addHeader("content-type", "application/json");
                    CloseableHttpResponse res;
                    while (true) {
                        try (BufferedReader reader = new BufferedReader(new FileReader(
                                QUERY_FILE_DIR + File.separator + random.nextInt(numQueries) + ".json"))) {
                            int length = reader.read(BUFFER);
                            post.setEntity(new StringEntity(new String(BUFFER, 0, length)));
                        }
                        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.hubrick.raml.mojo.util.JavaNames.java

private static <T> Function<T, Indexed<T>> indexed() {
    final AtomicInteger index = new AtomicInteger();
    return (value) -> new BasicIndexed<>(index.getAndIncrement(), value);
}

From source file:io.fluo.core.client.FluoClientImpl.java

public static final AutoCloseable setupReporters(Environment env, String id, AtomicInteger reporterCounter) {
    return ReporterUtil.setupReporters(env,
            FluoConfiguration.FLUO_PREFIX + "." + id + "." + reporterCounter.getAndIncrement());
}