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

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

Introduction

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

Prototype

public AtomicInteger(int initialValue) 

Source Link

Document

Creates a new AtomicInteger with the given initial value.

Usage

From source file:jms.PublisherThread.java

public PublisherThread(SimpleJMSPublisher publisher) {
    jmsPublisher = publisher;/*from www  .  ja v a  2s  .c o  m*/
    sentCount = new AtomicInteger(0);
    publishRate = Main.metrics
            .meter(name(PublisherThread.class, "publisher", publisher.getConfigs().getId(), "meter"));

    // Per given period how many messages were sent is taken through this gauge
    Main.gauges.register(name(PublisherThread.class, jmsPublisher.getConfigs().getId(), "sent-stats"),
            new Gauge<Integer>() {

                /**
                 * number of messages sent since last call to this method is returned
                 * @return Integer
                 */
                @Override
                public Integer getValue() {
                    int val = sentCount.get();
                    sentCount.addAndGet(-val);
                    return val;
                }
            });
}

From source file:lh.api.showcase.server.util.HttpQueryUtils.java

public static String executeQuery(URI uri, ApiAuth apiAuth, HasProxySettings proxySetting,
        HttpClientFactory httpClientFactory, final int maxRetries) throws HttpErrorResponseException {

    //logger.info("uri: " + uri.toString());

    AtomicInteger tryCounter = new AtomicInteger(0);
    while (true) {

        CloseableHttpClient httpclient = httpClientFactory.getHttpClient(proxySetting);
        HttpGet httpGet = new HttpGet(uri);
        httpGet.addHeader("Authorization", apiAuth.getAuthHeader());
        httpGet.addHeader("Accept", "application/json");

        //logger.info("auth: " + apiAuth.getAuthHeader()) ;
        //logger.info("query: " + httpGet.toString());

        CloseableHttpResponse response = null;
        try {/*w ww .  ja v a 2  s .  c  o m*/
            response = httpclient.execute(httpGet);
            StatusLine status = response.getStatusLine();
            BufferedHttpEntity entity = new BufferedHttpEntity(response.getEntity());
            String json = IOUtils.toString(entity.getContent(), "UTF8");
            EntityUtils.consume(entity);
            //logger.info("response: " + json);

            // check for errors
            if (status != null && status.getStatusCode() > 299) {
                if (status.getStatusCode() == 401) {
                    // token has probably expired
                    logger.info("Authentication Error. Token will be refreshed");
                    if (tryCounter.getAndIncrement() < maxRetries) {
                        if (apiAuth.updateAccessToken()) {
                            logger.info("Token successfully refreshed");
                            // we retry with the new token
                            logger.info("Retry number " + tryCounter.get());
                            continue;
                        }
                    }
                }
                throw new HttpErrorResponseException(status.getStatusCode(), status.getReasonPhrase(), json);
            }
            return json;
        } catch (IOException e) {
            logger.severe(e.getMessage());
            break;
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
            } catch (IOException e) {
                logger.log(Level.SEVERE, e.getMessage());
            }
        }
    }
    return null;
}

From source file:com.espertech.esper.epl.metric.MetricsExecutorThreaded.java

/**
 * Ctor.//from w w w  .j a  v a2s  .c  om
 * @param engineURI engine URI
 */
public MetricsExecutorThreaded(final String engineURI) {
    ThreadFactory threadFactory = new ThreadFactory() {
        AtomicInteger count = new AtomicInteger(0);

        public Thread newThread(Runnable r) {
            String uri = engineURI;
            if (engineURI == null) {
                uri = "default";
            }
            Thread t = new Thread(r);
            t.setName("com.espertech.esper.MetricReporting-" + uri + "-" + count.getAndIncrement());
            t.setDaemon(true);
            return t;
        }
    };
    threadPool = Executors.newCachedThreadPool(threadFactory);
}

From source file:org.elasticsearch.logstash.Server.java

public void start() throws InterruptedException {

    long start = System.nanoTime();

    AtomicInteger counter = new AtomicInteger(1);

    for (int i = 0; i < messageCount; i++) {
        /* wait for input -- e.g. wait on a NETTY pipeline input */
        //        JokeResource jokeResource = restTemplate.getForObject("http://api.icndb.com/jokes/random", JokeResource.class);

        final String message = String.format("message: %d", counter.getAndIncrement());
        inputReactor.notify(Pipeline.Stage.input, Event.wrap(message));
    }/*from  ww  w  .ja v a 2 s .co m*/

    latch.await();
    long elapsed = System.nanoTime() - start;

    System.out.println("Elapsed time: " + elapsed + "ns");
    System.out.println("Average pipeline process time per message: " + elapsed / messageCount + "ns");
}

From source file:com.unicodecollective.amsterdam.TokenBucket.java

public TokenBucket(int initialCapacity) {
    this.capacity = new AtomicInteger(initialCapacity);
    this.maximumCapacity = null;
}

From source file:jms.ConsumerThread.java

public ConsumerThread(SimpleJMSConsumer consumer, Histogram globalLatency, Meter globalConsumerRate) {
    jmsConsumer = consumer;//  www. j  a v a 2s. c om
    receivedCount = new AtomicInteger(0);
    latencyHist = Main.metrics
            .histogram(name(ConsumerThread.class, "consumer", jmsConsumer.getConfigs().getId(), "latency"));
    consumerRate = Main.metrics
            .meter(name(ConsumerThread.class, "consumer", jmsConsumer.getConfigs().getId(), "rate"));

    // Per given period how many messages were sent is taken through this gauge
    Main.gauges.register(name(ConsumerThread.class, jmsConsumer.getConfigs().getId(), "receiving-stats"),
            new Gauge<Integer>() {

                @Override
                public Integer getValue() {
                    int val = receivedCount.get();
                    receivedCount.addAndGet(-val);
                    return val;
                }
            });

    this.globalConsumerRate = globalConsumerRate;
    this.globalLatencyHist = globalLatency;
}

From source file:org.esigate.url.RoundRobinBaseUrlRetrieveStrategyTest.java

public void testGetBaseURL() {
    String[] baseUrls = new String[] { "http://example.com/test/", "http://example1.com/test/",
            "http://example2.com/test/" };
    BaseUrlRetrieveStrategy strategy = new RoundRobinBaseUrlRetrieveStrategy(baseUrls);
    IncomingRequest request = TestUtils.createIncomingRequest().build();
    int times = 5;
    int requestsCount = baseUrls.length * times;
    ConcurrentMap<String, AtomicInteger> counterMap = new ConcurrentHashMap<String, AtomicInteger>();
    for (int i = 0; i < requestsCount; i++) {
        String baseUrl = strategy.getBaseURL(request);
        counterMap.putIfAbsent(baseUrl, new AtomicInteger(0));
        counterMap.get(baseUrl).incrementAndGet();
    }/*from  w w  w . j a v  a  2 s.  c  o  m*/
    for (String baseUrl : baseUrls) {
        assertEquals(times, counterMap.get(baseUrl).get());
    }
}

From source file:CreateTest.java

static void doTestCreate() {
    done = false;//from   w  w  w  . j av a 2  s . c  o  m
    nCalls = new AtomicInteger(0);
    for (int i = 0; i < target; i++) {
        Thread t = new CreateTest();
        t.start();
    }
    synchronized (lock) {
        while (!done)
            try {
                lock.wait();
            } catch (Exception e) {
            }
    }
}

From source file:uk.ac.ebi.ep.parser.parsers.EnzymePortalPDBeParser.java

public void updatePDBeData() {

    Set<UniprotXref> entries = new HashSet<>();

    List<UniprotXref> pdbIds = parserService.findPDBcodes();
    LOGGER.info("Number of PDB entries to process : " + pdbIds.size());

    //int est = pdbIds.size()/500;

    Stream<UniprotXref> existingStream = pdbIds.stream();
    Stream<List<UniprotXref>> partitioned = partition(existingStream, 500, 1);
    AtomicInteger count = new AtomicInteger(1);
    partitioned.parallel().forEach((chunk) -> {

        chunk.stream().forEach((pdb) -> {
            //obtain a concrete pdb entry
            PdbSearchResult results = pdbService.getPdbSearchResults(pdb.getSourceId().toLowerCase());

            if (results != null) {
                List<PDBe> result = results.get(pdb.getSourceId().toLowerCase());
                String title = result.stream().findAny().get().getTitle();
                pdb.setSourceName(title);
                entries.add(pdb);//from  w w w .j av a2 s .c  o m
            }
        });
    });

    //        AtomicInteger count = new AtomicInteger(1);
    //        pdbIds.stream().forEach((pdb) -> {
    //            //obtain a concrete pdb entry
    //            PdbSearchResult results = pdbService.getPdbSearchResults(pdb.getSourceId().toLowerCase());
    //           // System.out.println("count "+count.getAndIncrement() +" PDB id "+ pdb.getSourceId());
    //            if (results != null) {
    //                List<PDBe> result = results.get(pdb.getSourceId().toLowerCase());
    //                String title = result.stream().findAny().get().getTitle();
    //                pdb.setSourceName(title);
    //                entries.add(pdb);
    //            }
    //        });

    //update entry
    List<UniprotXref> pdbEntries = entries.stream().collect(Collectors.toList());

    List<UniprotXref> updatedEntries = parserService.updatePDB(pdbEntries);
    LOGGER.info("Number of PDB entries updated are : " + updatedEntries.size());
    updatedEntries.clear();
}

From source file:Main.java

public static ThreadFactory newGenericThreadFactory(final String processName, final int threads,
        final boolean isDaemon) {
    return new ThreadFactory() {
        private AtomicInteger threadIndex = new AtomicInteger(0);

        @Override/*from www.  j av a2s  . com*/
        public Thread newThread(Runnable r) {
            Thread thread = new Thread(r,
                    String.format("%s_%d_%d", processName, threads, this.threadIndex.incrementAndGet()));
            thread.setDaemon(isDaemon);
            return thread;
        }
    };
}