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:ufo.remote.calls.benchmark.client.caller.hornetq.HornetQTester.java

@Override
protected void startTest(final TesterResult result) {

    ProducerTemplate producerTemplate = camelContext.createProducerTemplate();
    producerTemplate.setExecutorService(Executors.newFixedThreadPool(20));

    String url = HornetQApacheCamelConfig.JMS_NAME
            + ":queue:echo?deliveryPersistent=false&replyToDeliveryPersistent=false";
    AtomicInteger failures = new AtomicInteger(0);
    CountDownLatch latch = new CountDownLatch(result.totalCalls);

    for (int i = 0; i < result.totalCalls; i++) {
        producerTemplate.asyncCallbackRequestBody(url, result.message, new Synchronization() {

            @Override//  ww w.  ja  v  a2 s  .c o m
            public void onFailure(final Exchange exchange) {
                failures.incrementAndGet();
                latch.countDown();
            }

            @Override
            public void onComplete(final Exchange exchange) {
                if (logger.isDebugEnabled()) {
                    logger.debug("Received message [{}]", exchange.getIn().getBody());
                }
                latch.countDown();
            }
        });
    }

    try {
        latch.await();
    } catch (InterruptedException e) {
        throw new RuntimeException(e);
    }
    result.failures = failures.get();

}

From source file:com.palantir.docker.compose.DockerComposeRuleShould.java

@Test
public void pass_wait_for_service_when_check_is_true_after_being_false()
        throws IOException, InterruptedException {
    AtomicInteger timesCheckCalled = new AtomicInteger(0);
    withComposeExecutableReturningContainerFor("db");
    HealthCheck<Container> checkCalledTwice = (container) -> SuccessOrFailure
            .fromBoolean(timesCheckCalled.incrementAndGet() == 2, "not called twice yet");
    DockerComposeRule.builder().from(rule).waitingForService("db", checkCalledTwice).build().before();
    assertThat(timesCheckCalled.get(), is(2));
}

From source file:com.weibo.datasys.crawler.impl.strategy.rule.save.StatisticSaveRule.java

@Override
public Null apply(ParseInfo in) {
    String url = in.getThisCrawlInfo().getSeedData().getUrl();
    String host = URLUtil.getHost(url);
    AtomicInteger count = hostCountMap.get(host);
    if (count == null) {
        synchronized (StatisticSaveRule.class) {
            if (count == null) {
                count = new AtomicInteger();
                hostCountMap.put(host, count);
            } else {
                count = hostCountMap.get(host);
            }//ww w  .j a va2  s.  co m
        }
    }
    count.incrementAndGet();
    saveResult();
    return null;
}

From source file:org.apache.hadoop.gateway.rm.dispatch.RMHaBaseDispatcher.java

private void retryRequest(HttpUriRequest outboundRequest, HttpServletRequest inboundRequest,
        HttpServletResponse outboundResponse, HttpResponse inboundResponse, Exception exception)
        throws IOException {
    LOG.retryingRequest(outboundRequest.getURI().toString());
    AtomicInteger counter = (AtomicInteger) inboundRequest.getAttribute(RETRY_COUNTER_ATTRIBUTE);
    if (counter == null) {
        counter = new AtomicInteger(0);
    }//from  w w  w  .j a v a 2  s.  c om
    inboundRequest.setAttribute(RETRY_COUNTER_ATTRIBUTE, counter);
    if (counter.incrementAndGet() <= maxRetryAttempts) {
        if (retrySleep > 0) {
            try {
                Thread.sleep(retrySleep);
            } catch (InterruptedException e) {
                LOG.retrySleepFailed(this.resourceRole, e);
            }
        }
        executeRequest(outboundRequest, inboundRequest, outboundResponse);
    } else {
        LOG.maxRetryAttemptsReached(maxRetryAttempts, this.resourceRole, outboundRequest.getURI().toString());
        if (inboundResponse != null) {
            writeOutboundResponse(outboundRequest, inboundRequest, outboundResponse, inboundResponse);
        } else {
            throw new IOException(exception);
        }
    }
}

From source file:ws.antonov.config.consumer.ConfigClientTest.java

@SuppressWarnings({ "unchecked" })
public void testCachingConfigClientWrapper() throws Exception {
    FileInputStream fis = new FileInputStream("build/classes/test/config.pb");
    final FlatConfigObject msg = FlatConfigObject.parseFrom(fis);
    final AtomicInteger accessCount = new AtomicInteger(0);
    ConfigClient client = new ConfigClient() {
        @Override//from  w w w .  j  av  a2  s  .c o m
        public Message getConfig(Class configClass, ConfigParamsBuilder.ConfigParamsMap configParams) {
            accessCount.incrementAndGet();
            if (configParams.size() == 0)
                return msg;
            else
                return null;
        }

        @Override
        public ConfigProvider getConfigProvider() {
            return null;
        }

        @Override
        public boolean reloadConfig() {
            return true;
        }
    };
    Map objects = new HashMap();
    Set keys = new HashSet();
    CachingConfigClientWrapper cachingConfig = new CachingConfigClientWrapper(client, objects, keys);

    assertEquals(0, accessCount.get());
    assertEquals(0, cachingConfig.getObjectCache().size());
    assertEquals(0, cachingConfig.getNegativeCache().size());

    assertEquals(cachingConfig.getConfig(FlatConfigObject.class, ConfigParamsBuilder.newInstance().build()),
            msg);
    assertEquals(1, accessCount.get());
    assertEquals(1, cachingConfig.getObjectCache().size());
    assertEquals(0, cachingConfig.getNegativeCache().size());

    assertEquals(cachingConfig.getConfig(FlatConfigObject.class, ConfigParamsBuilder.newInstance().build()),
            msg);
    assertEquals(1, accessCount.get());
    assertEquals(1, cachingConfig.getObjectCache().size());
    assertEquals(0, cachingConfig.getNegativeCache().size());

    assertNull(cachingConfig.getConfig(FlatConfigObject.class,
            ConfigParamsBuilder.newInstance("foo", "bar").build()));
    assertEquals(2, accessCount.get());
    assertEquals(1, cachingConfig.getObjectCache().size());
    assertEquals(1, cachingConfig.getNegativeCache().size());

    assertNull(cachingConfig.getConfig(FlatConfigObject.class,
            ConfigParamsBuilder.newInstance("foo", "bar").build()));
    assertEquals(2, accessCount.get());
    assertEquals(1, cachingConfig.getObjectCache().size());
    assertEquals(1, cachingConfig.getNegativeCache().size());
}

From source file:com.comcast.cdn.traffic_control.traffic_router.core.router.StatelessTrafficRouterPerformanceTest.java

public URL routeTest(final HTTPRequest request, String[] rstrs)
        throws TrafficRouterException, GeolocationException {
    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("Attempting to route HTTPRequest: " + request.getRequestedUrl());
    }//  w w  w. j  a  v  a  2 s  .c o m

    final String ip = request.getClientIP();
    final DeliveryService ds = selectDeliveryService(request, true);
    if (ds == null) {
        return null;
    }
    final StatTracker.Track track = StatTracker.getTrack();
    List<Cache> caches = selectCache(request, ds, track);
    Dispersion dispersion = ds.getDispersion();
    Cache cache = dispersion.getCache(consistentHash(caches, request.getPath()));
    try {
        if (cache != null) {
            return new URL(ds.createURIString(request, cache));
        }
    } catch (final MalformedURLException e) {
        LOGGER.error(e.getMessage(), e);
        throw new TrafficRouterException(URL_ERR_STR, e);
    }
    LOGGER.warn("No Cache found in CoverageZoneMap for HTTPRequest.getClientIP: " + ip);

    final String zoneId = null;
    Geolocation clientLocation = getGeolocationService().location(request.getClientIP());
    final List<CacheLocation> cacheLocations = orderCacheLocations(getCacheRegister().getCacheLocations(zoneId),
            ds, clientLocation);
    for (final CacheLocation location : cacheLocations) {
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("Trying location: " + location.getId());
        }

        caches = getSupportingCaches(location.getCaches(), ds);
        if (caches.isEmpty()) {
            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug("No online, supporting caches were found at location: " + location.getId());
            }
            return null;
        }

        cache = dispersion.getCache(consistentHash(caches, request.getPath()));
        LOGGER.warn("cache selected: " + cache.getId());

        Map<String, AtomicInteger> m = new HashMap<String, AtomicInteger>();
        long time = System.currentTimeMillis();
        for (String str : rstrs) {
            cache = dispersion.getCache(consistentHash(caches, str));
            AtomicInteger i = m.get(cache.getId());
            if (i == null) {
                i = new AtomicInteger(0);
                m.put(cache.getId(), i);
            }
            i.incrementAndGet();
        }
        time = System.currentTimeMillis() - time;
        LOGGER.warn(String.format("time: %d", time));
        for (String id : m.keySet()) {
            LOGGER.warn(String.format("cache(%s): %d", id, m.get(id).get()));
        }

        m = new HashMap<String, AtomicInteger>();
        time = System.currentTimeMillis();
        for (String str : rstrs) {
            cache = consistentHashOld(caches, str);
            AtomicInteger i = m.get(cache.getId());
            if (i == null) {
                i = new AtomicInteger(0);
                m.put(cache.getId(), i);
            }
            i.incrementAndGet();
        }
        time = System.currentTimeMillis() - time;
        LOGGER.warn(String.format("time: %d", time));
        for (String id : m.keySet()) {
            LOGGER.warn(String.format("cache(%s): %d", id, m.get(id).get()));
        }

        if (cache != null) {
            try {
                return new URL(ds.createURIString(request, cache));

            } catch (final MalformedURLException e) {
                LOGGER.error(e.getMessage(), e);
                throw new TrafficRouterException(URL_ERR_STR, e);
            }
        }
    }

    LOGGER.info(UNABLE_TO_ROUTE_REQUEST);
    throw new TrafficRouterException(UNABLE_TO_ROUTE_REQUEST);
}

From source file:com.twitter.distributedlog.auditor.DLAuditor.java

static <T> void executeAction(final LinkedBlockingQueue<T> queue, final int numThreads, final Action<T> action)
        throws IOException {
    final CountDownLatch failureLatch = new CountDownLatch(1);
    final CountDownLatch doneLatch = new CountDownLatch(queue.size());
    final AtomicInteger numFailures = new AtomicInteger(0);
    final AtomicInteger completedThreads = new AtomicInteger(0);

    ExecutorService executorService = Executors.newFixedThreadPool(numThreads);
    try {//w ww  .j  av  a 2  s . c o  m
        for (int i = 0; i < numThreads; i++) {
            executorService.submit(new Runnable() {
                @Override
                public void run() {
                    while (true) {
                        T item = queue.poll();
                        if (null == item) {
                            break;
                        }
                        try {
                            action.execute(item);
                        } catch (IOException ioe) {
                            logger.error("Failed to execute action on item '{}'", item, ioe);
                            numFailures.incrementAndGet();
                            failureLatch.countDown();
                            break;
                        }
                        doneLatch.countDown();
                    }
                    if (numFailures.get() == 0 && completedThreads.incrementAndGet() == numThreads) {
                        failureLatch.countDown();
                    }
                }
            });
        }
        try {
            failureLatch.await();
            if (numFailures.get() > 0) {
                throw new IOException("Encountered " + numFailures.get() + " failures on executing action.");
            }
            doneLatch.await();
        } catch (InterruptedException ie) {
            Thread.currentThread().interrupt();
            logger.warn("Interrupted on executing action", ie);
            throw new DLInterruptedException("Interrupted on executing action", ie);
        }
    } finally {
        executorService.shutdown();
    }
}

From source file:com.zimbra.cs.servlet.ContextPathBasedThreadPoolBalancerFilter.java

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {

    // Determine whether to allow or suspend request
    boolean suspend = shouldSuspend(request);

    // Suspend request
    if (suspend) {
        Continuation continuation = ContinuationSupport.getContinuation(request);
        HttpServletRequest hreq = (HttpServletRequest) request;
        ZimbraServlet.addRemoteIpToLoggingContext(hreq);
        ZimbraServlet.addUAToLoggingContext(hreq);
        ZimbraLog.clearContext();//  w  ww  .  j  ava 2s . c o m
        continuation.setTimeout(suspendMs);
        continuation.suspend();
        return;
    }

    // Allow request
    String contextPath = getContextPath(request);
    try {
        // Start tracking request
        AtomicInteger i = activeRequestsByContextPath.get(contextPath);
        if (i == null) {
            i = new AtomicInteger(1);
            activeRequestsByContextPath.put(contextPath, i);
        } else {
            i.incrementAndGet();
        }
        //            ZimbraLog.misc.debug("%s concurrency=%d", contextPath, i.get());

        // Perform default operation
        chain.doFilter(request, response);

    } finally {
        // Stop tracking request
        AtomicInteger i = activeRequestsByContextPath.get(contextPath);
        i.decrementAndGet();
        //            ZimbraLog.misc.debug("%s concurrency=%d", contextPath, i.get());
    }
}

From source file:org.apache.synapse.transport.fix.FIXIncomingMessageHandler.java

/**
 * This callback receives messages for the application. This is one of the
 * core entry points for the FIX application. Every application level
 * request will come through here. A new thread will be spawned from the
 * thread pool for each incoming message.
 *
 * @param message QuickFIX message//from   ww w. j a  v a  2 s.  c  om
 * @param sessionID QuickFIX session ID
 * @throws FieldNotFound
 * @throws IncorrectDataFormat
 * @throws IncorrectTagValue
 * @throws UnsupportedMessageType
 */
public void fromApp(Message message, SessionID sessionID)
        throws FieldNotFound, IncorrectDataFormat, IncorrectTagValue, UnsupportedMessageType {
    if (log.isDebugEnabled()) {
        StringBuffer sb = new StringBuffer();
        sb.append("Received FIX message from ")
                .append(message.getHeader().getField(new SenderCompID()).getValue());
        sb.append("\nMessage Sequence Number: ")
                .append(message.getHeader().getField(new MsgSeqNum()).getValue());
        sb.append("\nReceiver ID: ").append(message.getHeader().getField(new TargetCompID()).getValue());
        log.debug(sb.toString());
        if (log.isTraceEnabled()) {
            log.trace("Message: " + message.toString());
        }
    }

    AtomicInteger atomicCounter = countersMap.get(sessionID);
    int counter = atomicCounter.incrementAndGet();
    boolean rolled = atomicCounter.compareAndSet(FIXConstants.DEFAULT_COUNTER_UPPER_LIMIT, 0);
    if (rolled && log.isDebugEnabled()) {
        log.debug("Incoming request counter rolled over for the session: " + sessionID);
    }
    workerPool.execute(new FIXWorkerThread(message, sessionID, counter));
}

From source file:com.streamsets.pipeline.stage.origin.spooldir.TestWholeFileSpoolDirSource.java

@Test
public void testWholeFileRecordsCopy() throws Exception {
    Path sourcePath = Paths.get(testDir + "/source.txt");
    Files.write(sourcePath, "Sample Text 1".getBytes());
    SpoolDirSource source = createSource();
    PushSourceRunner runner = new PushSourceRunner.Builder(SpoolDirDSource.class, source).addOutputLane("lane")
            .setOnRecordError(OnRecordError.TO_ERROR).build();

    final List<Record> records = Collections.synchronizedList(new ArrayList<>(10));
    AtomicInteger batchCount = new AtomicInteger(0);

    runner.runInit();/* w  w w.j av a2  s  .  c  o m*/

    try {
        runner.runProduce(new HashMap<>(), 10, output2 -> {
            synchronized (records) {
                records.addAll(output2.getRecords().get("lane"));
            }
            batchCount.incrementAndGet();
            runner.setStop();
        });
        runner.waitOnProduce();

        Assert.assertNotNull(records);
        Assert.assertEquals(1, records.size());
        Record record = records.get(0);
        Assert.assertTrue(record.has(FileRefUtil.FILE_INFO_FIELD_PATH));
        Assert.assertTrue(record.has(FileRefUtil.FILE_REF_FIELD_PATH));

        FileRef fileRef = record.get(FileRefUtil.FILE_REF_FIELD_PATH).getValueAsFileRef();
        String targetFile = testDir + "/target.txt";
        Stage.Context context = (Stage.Context) Whitebox.getInternalState(source, "context");

        initMetrics(context);

        IOUtils.copy(fileRef.createInputStream(context, InputStream.class), new FileOutputStream(targetFile));
        //Now make sure the file is copied properly,
        checkFileContent(new FileInputStream(sourcePath.toString()), new FileInputStream(targetFile));
    } finally {
        runner.runDestroy();
    }
}