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

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

Introduction

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

Prototype

public final int incrementAndGet() 

Source Link

Document

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

Usage

From source file:org.apache.hadoop.hive.ql.parse.TezCompiler.java

private void connect(Operator<?> o, AtomicInteger index, Stack<Operator<?>> nodes,
        Map<Operator<?>, Integer> indexes, Map<Operator<?>, Integer> lowLinks,
        Set<Set<Operator<?>>> components) {

    indexes.put(o, index.get());//from   w  w w  .ja  va  2s.  c  o  m
    lowLinks.put(o, index.get());
    index.incrementAndGet();
    nodes.push(o);

    List<Operator<?>> children;
    if (o instanceof AppMasterEventOperator) {
        children = new ArrayList<Operator<?>>();
        children.addAll(o.getChildOperators());
        TableScanOperator ts = ((DynamicPruningEventDesc) o.getConf()).getTableScan();
        LOG.debug("Adding special edge: " + o.getName() + " --> " + ts.toString());
        children.add(ts);
    } else {
        children = o.getChildOperators();
    }

    for (Operator<?> child : children) {
        if (!indexes.containsKey(child)) {
            connect(child, index, nodes, indexes, lowLinks, components);
            lowLinks.put(o, Math.min(lowLinks.get(o), lowLinks.get(child)));
        } else if (nodes.contains(child)) {
            lowLinks.put(o, Math.min(lowLinks.get(o), indexes.get(child)));
        }
    }

    if (lowLinks.get(o).equals(indexes.get(o))) {
        Set<Operator<?>> component = new HashSet<Operator<?>>();
        components.add(component);
        Operator<?> current;
        do {
            current = nodes.pop();
            component.add(current);
        } while (current != o);
    }
}

From source file:no.difi.sdp.client.asice.signature.CreateSignatureTest.java

@Test
public void multithreaded_signing() throws Exception {
    List<Thread> threads = new ArrayList<Thread>();
    final AtomicInteger fails = new AtomicInteger(0);
    for (int i = 0; i < 50; i++) {
        Thread t = new Thread() {
            @Override//from w w w  . j av  a  2  s  .  c o m
            public void run() {
                for (int j = 0; j < 20; j++) {
                    Signature signature = sut.createSignature(noekkelpar, files);
                    if (!verify_signature(signature)) {
                        fails.incrementAndGet();
                    }
                    if (fails.get() > 0) {
                        break;
                    }
                }
            }
        };
        threads.add(t);
        t.start();
    }
    for (Thread t : threads) {
        t.join();
    }
    if (fails.get() > 0) {
        fail("Signature validation failed");
    }
}

From source file:com.android.tools.idea.editors.theme.ThemeEditorUtilsTest.java

public void testResourceResolverVisitor() {
    myFixture.copyFileToProject("themeEditor/apiTestBefore/stylesApi-v14.xml", "res/values-v14/styles.xml");
    myFixture.copyFileToProject("themeEditor/apiTestBefore/stylesApi-v19.xml", "res/values-v19/styles.xml");
    myFixture.copyFileToProject("themeEditor/apiTestBefore/stylesApi-v21.xml", "res/values-v21/styles.xml");

    final AtomicInteger visitedRepos = new AtomicInteger(0);
    // With only one source set, this should be called just once.
    ThemeEditorUtils.acceptResourceResolverVisitor(myFacet, new ThemeEditorUtils.ResourceFolderVisitor() {
        @Override//from w w w  . j a v  a2s . c  o m
        public void visitResourceFolder(@NotNull LocalResourceRepository resources, String moduleName,
                @NotNull String variantName, boolean isSelected) {
            assertEquals("main", variantName);
            visitedRepos.incrementAndGet();
        }
    });
    assertEquals(1, visitedRepos.get());
    // TODO: Test variants
}

From source file:com.couchbase.client.core.endpoint.view.ViewHandlerTest.java

@Test
public void shouldDecodeEmptyViewQueryResponse() throws Exception {
    String response = Resources.read("query_empty.json", this.getClass());
    HttpResponse responseHeader = new DefaultHttpResponse(HttpVersion.HTTP_1_1,
            new HttpResponseStatus(200, "OK"));
    HttpContent responseChunk = new DefaultLastHttpContent(Unpooled.copiedBuffer(response, CharsetUtil.UTF_8));

    ViewQueryRequest requestMock = mock(ViewQueryRequest.class);
    queue.add(requestMock);// w ww  .  j  av a 2 s .  c  o m
    channel.writeInbound(responseHeader, responseChunk);
    latch.await(1, TimeUnit.SECONDS);
    assertEquals(1, firedEvents.size());
    ViewQueryResponse inbound = (ViewQueryResponse) firedEvents.get(0);

    assertTrue(inbound.status().isSuccess());
    assertTrue(inbound.rows().toList().toBlocking().single().isEmpty());

    final AtomicInteger called = new AtomicInteger();
    inbound.info().toBlocking().forEach(new Action1<ByteBuf>() {
        @Override
        public void call(ByteBuf byteBuf) {
            called.incrementAndGet();
            assertEquals("{\"total_rows\":7303}", byteBuf.toString(CharsetUtil.UTF_8));
        }
    });
    assertEquals(1, called.get());
}

From source file:com.inmobi.grill.driver.hive.TestRemoteHiveDriver.java

@Test
public void testMultiThreadClient() throws Exception {
    LOG.info("@@ Starting multi thread test");
    // Launch two threads
    createTestTable("test_multithreads");
    HiveConf thConf = new HiveConf(conf, TestRemoteHiveDriver.class);
    thConf.setLong(HiveDriver.GRILL_CONNECTION_EXPIRY_DELAY, 10000);
    final HiveDriver thrDriver = new HiveDriver();
    thrDriver.configure(thConf);//from w ww . j  a va2  s  .  c o m
    QueryContext ctx = new QueryContext("USE " + TestRemoteHiveDriver.class.getSimpleName(), null, conf);
    thrDriver.execute(ctx);

    // Launch a select query
    final int QUERIES = 5;
    int launchedQueries = 0;
    final int THREADS = 5;
    final long POLL_DELAY = 500;
    List<Thread> thrs = new ArrayList<Thread>();
    final AtomicInteger errCount = new AtomicInteger();
    for (int q = 0; q < QUERIES; q++) {
        final QueryContext qctx;
        try {
            qctx = new QueryContext("SELECT * FROM test_multithreads", null, conf);
            thrDriver.executeAsync(qctx);
        } catch (GrillException e) {
            errCount.incrementAndGet();
            LOG.info(q + " executeAsync error: " + e.getCause());
            continue;
        }
        LOG.info("@@ Launched query: " + q + " " + qctx.getQueryHandle());
        launchedQueries++;
        // Launch many threads to poll for status
        final QueryHandle handle = qctx.getQueryHandle();

        for (int i = 0; i < THREADS; i++) {
            int thid = q * THREADS + i;
            Thread th = new Thread(new Runnable() {
                @Override
                public void run() {
                    for (int i = 0; i < 1000; i++) {
                        try {
                            thrDriver.updateStatus(qctx);
                            if (qctx.getDriverStatus().isFinished()) {
                                LOG.info("@@ " + handle.getHandleId() + " >> "
                                        + qctx.getDriverStatus().getState());
                                thrDriver.closeQuery(handle);
                                break;
                            }
                            Thread.sleep(POLL_DELAY);
                        } catch (GrillException e) {
                            LOG.error("Got Exception", e.getCause());
                            e.printStackTrace();
                            errCount.incrementAndGet();
                            break;
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                            break;
                        }
                    }
                }
            });
            thrs.add(th);
            th.setName("Poller#" + (thid));
            th.start();
        }
    }

    for (Thread th : thrs) {
        try {
            th.join(10000);
        } catch (InterruptedException e) {
            LOG.warn("Not ended yet: " + th.getName());
        }
    }
    Assert.assertEquals(0, thrDriver.getHiveHandleSize());
    LOG.info("@@ Completed all pollers. Total thrift errors: " + errCount.get());
    assertEquals(launchedQueries, QUERIES);
    assertEquals(thrs.size(), QUERIES * THREADS);
    assertEquals(errCount.get(), 0);
}

From source file:com.neatresults.mgnltweaks.app.status.ConfigStatusPresenter.java

@Override
public void refreshData() {
    List<String> fails = new ArrayList<String>();
    final AtomicInteger totalCount = new AtomicInteger();
    final AtomicInteger absCount = new AtomicInteger();
    final AtomicInteger overrideCount = new AtomicInteger();
    try {/*from  ww w .  j ava  2s.co  m*/
        Session session = MgnlContext.getJCRSession(RepositoryConstants.CONFIG);
        NodeIterator results = QueryUtil.search(RepositoryConstants.CONFIG,
                "select * from [nt:base] where extends is not null");
        filterData(results, n -> {
            try {
                String path = n.getProperty("extends").getString();
                if (StringUtils.startsWith(path, "/")) {
                    absCount.incrementAndGet();
                    return session.itemExists(path);
                } else if ("override".equals(path)) {
                    overrideCount.incrementAndGet();
                    return true;
                } else {
                    return session.itemExists(n.getPath() + "/" + path);
                }
            } catch (RepositoryException e) {
                log.debug("Ooops, error while checking existence of extends target for {} with {}", n,
                        e.getMessage(), e);
                return false;
            }
        }, t -> totalCount.incrementAndGet(), f -> {
            try {
                fails.add(f.getPath());
            } catch (RepositoryException e) {
                log.debug("Ooops, error while reporting misconfigured extends target for {} with {}", f,
                        e.getMessage(), e);
            }
        });
    } catch (RepositoryException e) {
        log.debug("Ooops, error while searching for extends targets with {}", e.getMessage(), e);
    }
    sourceData(ConfigStatusView.EXTENDS_FAIL_COUNT, "" + fails.size());
    sourceData(ConfigStatusView.EXTENDS_FAIL_LIST, fails);
    sourceData(ConfigStatusView.EXTENDS_COUNT, "" + totalCount.get());
    sourceData(ConfigStatusView.ABS_EXTENDS_COUNT, "" + absCount.get());
    sourceData(ConfigStatusView.REL_EXTENDS_COUNT,
            "" + (totalCount.get() - absCount.get() - overrideCount.get()));
    sourceData(ConfigStatusView.OVR_EXTENDS_COUNT, "" + overrideCount.get());
}

From source file:com.googlecode.fightinglayoutbugs.FightingLayoutBugs.java

private void registerDebugListener() {
    final AtomicInteger i = new AtomicInteger(0);
    final NumberFormat nf = new DecimalFormat("00");
    final File screenshotDir = this.screenshotDir;
    final Visualization.Listener debugListener = new Visualization.Listener() {
        @Override/*from  w  w  w.  j a v a 2  s .co m*/
        public void algorithmStepFinished(String algorithm, String stepDescription, int[][] tempResult) {
            File pngFile = new File(screenshotDir, nf.format(i.incrementAndGet()) + "_" + algorithm + ".png");
            ImageHelper.pixelsToPngFile(tempResult, pngFile);
            LOG.debug(pngFile.getName() + " -- " + stepDescription);
        }

        @Override
        public void algorithmFinished(String algorithm, String stepDescription, int[][] result) {
            File pngFile = new File(screenshotDir, nf.format(i.incrementAndGet()) + "_" + algorithm + ".png");
            ImageHelper.pixelsToPngFile(result, pngFile);
            LOG.debug(pngFile.getName() + " -- " + stepDescription);
        }
    };
    Visualization.registerListener(debugListener);
    _runAfterAnalysis.add(new Runnable() {
        @Override
        public void run() {
            Visualization.unregisterListener(debugListener);
        }
    });
}

From source file:org.apache.tinkerpop.gremlin.driver.util.ProfilingApplication.java

public long execute() throws Exception {
    final AtomicInteger tooSlow = new AtomicInteger(0);

    final Client client = cluster.connect();
    final String executionId = "[" + executionName + "]";
    try {//from  w w  w .  ja v  a  2  s.c  om
        final CountDownLatch latch = new CountDownLatch(requests);
        client.init();

        final long start = System.nanoTime();
        IntStream.range(0, requests).forEach(i -> client.submitAsync(script).thenAcceptAsync(r -> {
            try {
                r.all().get(tooSlowThreshold, TimeUnit.MILLISECONDS);
            } catch (TimeoutException ex) {
                tooSlow.incrementAndGet();
            } catch (Exception ex) {
                ex.printStackTrace();
            } finally {
                latch.countDown();
            }
        }, executor));

        // finish once all requests are accounted for
        latch.await();

        final long end = System.nanoTime();
        final long total = end - start;
        final double totalSeconds = total / 1000000000d;
        final long requestCount = requests;
        final long reqSec = Math.round(requestCount / totalSeconds);
        System.out.println(String.format(
                StringUtils.rightPad(executionId, 10)
                        + " requests: %s | time(s): %s | req/sec: %s | too slow: %s",
                requestCount, StringUtils.rightPad(String.valueOf(totalSeconds), 14),
                StringUtils.rightPad(String.valueOf(reqSec), 7), tooSlow.get()));
        return reqSec;
    } catch (Exception ex) {
        ex.printStackTrace();
        throw new RuntimeException(ex);
    } finally {
        client.close();
    }
}

From source file:org.jtheque.file.FileServiceTest.java

@Test
public void exporters() {
    final AtomicInteger counter = new AtomicInteger(0);

    final Collection<String> datas = Arrays.asList("data1", "data2", "data3");

    fileService.registerExporter("no-module", new Exporter<String>() {
        @Override//from w  w w  .  j av  a  2  s  .c  o  m
        public boolean canExportTo(String fileType) {
            return "xml".equals(fileType);
        }

        @Override
        public void export(String path, Collection<String> exportedDatas) throws FileException {
            counter.incrementAndGet();

            assertEquals("path", path);

            assertEquals(datas, exportedDatas);
        }
    });

    try {
        fileService.exportDatas("no-module", "xml", "path", datas);
    } catch (FileException e) {
        fail("Exception during the export");
    }

    assertEquals(1, counter.get());
}

From source file:com.mirth.connect.plugins.dashboardstatus.DashboardConnectorEventListener.java

@Override
protected void processEvent(Event event) {
    if (event instanceof ConnectionStatusEvent) {
        ConnectionStatusEvent connectionStatusEvent = (ConnectionStatusEvent) event;
        String channelId = connectionStatusEvent.getChannelId();
        Integer metaDataId = connectionStatusEvent.getMetaDataId();
        String information = connectionStatusEvent.getMessage();
        Timestamp timestamp = new Timestamp(event.getDateTime());

        String connectorId = channelId + "_" + metaDataId;

        ConnectionStatusEventType eventType = connectionStatusEvent.getState();

        ConnectionStatusEventType connectionStatusEventType = eventType;
        Integer connectorCount = null;
        Integer maximum = null;/* w ww  . j a va 2s  . c  o m*/

        if (event instanceof ConnectorCountEvent) {
            ConnectorCountEvent connectorCountEvent = (ConnectorCountEvent) connectionStatusEvent;

            maximum = connectorCountEvent.getMaximum();
            Boolean increment = connectorCountEvent.isIncrement();

            if (maximum != null) {
                maxConnectionMap.put(connectorId, maximum);
            } else {
                maximum = maxConnectionMap.get(connectorId);
            }

            AtomicInteger count = connectorCountMap.get(connectorId);

            if (count == null) {
                count = new AtomicInteger();
                connectorCountMap.put(connectorId, count);
            }

            if (increment != null) {
                if (increment) {
                    count.incrementAndGet();
                } else {
                    count.decrementAndGet();
                }
            }

            connectorCount = count.get();

            if (connectorCount == 0) {
                connectionStatusEventType = ConnectionStatusEventType.IDLE;
            } else {
                connectionStatusEventType = ConnectionStatusEventType.CONNECTED;
            }
        }

        String stateString = null;
        if (connectionStatusEventType.isState()) {
            Color color = getColor(connectionStatusEventType);
            stateString = connectionStatusEventType.toString();
            if (connectorCount != null) {
                if (maximum != null && connectorCount.equals(maximum)) {
                    stateString += " <font color='red'>(" + connectorCount + ")</font>";
                } else if (connectorCount > 0) {
                    stateString += " (" + connectorCount + ")";
                }
            }

            connectorStateMap.put(connectorId, new Object[] { color, stateString });
        }

        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss.SSS");
        String channelName = "";
        String connectorType = "";

        LinkedList<String[]> channelLog = null;

        Channel channel = ControllerFactory.getFactory().createChannelController()
                .getDeployedChannelById(channelId);

        if (channel != null) {
            channelName = channel.getName();
            // grab the channel's log from the HashMap, if not exist, create
            // one.
            if (connectorInfoLogs.containsKey(channelId)) {
                channelLog = connectorInfoLogs.get(channelId);
            } else {
                channelLog = new LinkedList<String[]>();
            }

            if (metaDataId == 0) {
                connectorType = "Source: " + channel.getSourceConnector().getTransportName() + "  ("
                        + channel.getSourceConnector().getTransformer().getInboundDataType().toString() + " -> "
                        + channel.getSourceConnector().getTransformer().getOutboundDataType().toString() + ")";
            } else {
                Connector connector = getConnectorFromMetaDataId(channel.getDestinationConnectors(),
                        metaDataId);
                connectorType = "Destination: " + connector.getTransportName() + " - " + connector.getName();
            }
        }

        if (channelLog != null) {
            synchronized (this) {
                if (channelLog.size() == MAX_LOG_SIZE) {
                    channelLog.removeLast();
                }
                channelLog.addFirst(
                        new String[] { String.valueOf(logId), channelName, dateFormat.format(timestamp),
                                connectorType, ((ConnectionStatusEvent) event).getState().toString(),
                                information, channelId, Integer.toString(metaDataId) });

                if (entireConnectorInfoLogs.size() == MAX_LOG_SIZE) {
                    entireConnectorInfoLogs.removeLast();
                }
                entireConnectorInfoLogs.addFirst(
                        new String[] { String.valueOf(logId), channelName, dateFormat.format(timestamp),
                                connectorType, ((ConnectionStatusEvent) event).getState().toString(),
                                information, channelId, Integer.toString(metaDataId) });

                logId++;

                // put the channel log into the HashMap.
                connectorInfoLogs.put(channelId, channelLog);
            }
        }

    }
}