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() 

Source Link

Document

Creates a new AtomicInteger with initial value 0 .

Usage

From source file:com.github.rvesse.airline.io.printers.UsagePrinter.java

public UsagePrinter(PrintWriter out, int maxSize) {
    this(out, maxSize, 0, 0, new AtomicInteger());
}

From source file:com.cyberway.issue.io.arc.ARCWriterPool.java

/**
 * Constructor/*from   w  w w.j  a  va2 s.  co m*/
 *
 * @param settings Settings for this pool.
 * @param poolMaximumActive
 * @param poolMaximumWait
 */
public ARCWriterPool(final WriterPoolSettings settings, final int poolMaximumActive,
        final int poolMaximumWait) {
    this(new AtomicInteger(), settings, poolMaximumActive, poolMaximumWait);
}

From source file:com.cyberway.issue.io.warc.WARCWriterPool.java

/**
 * Constructor//from  w ww .  ja v  a2 s .c o m
 * @param settings Settings for this pool.
 * @param poolMaximumActive
 * @param poolMaximumWait
 */
public WARCWriterPool(final WriterPoolSettings settings, final int poolMaximumActive,
        final int poolMaximumWait) {
    this(new AtomicInteger(), settings, poolMaximumActive, poolMaximumWait);
}

From source file:oz.hadoop.yarn.api.core.CommandProcessLauncher.java

/**
 * /*from w w w  .j av a2 s. c om*/
 * @param command
 * @param containerLivelinesBarrier
 */
public CommandProcessLauncher(String command) {
    super();
    Assert.hasText(command, "'command' must not be null or empty");
    this.command = command;
    this.streamsFinished = new AtomicInteger();
}

From source file:com.norconex.committer.AbstractFileQueueCommitterTest.java

@Test
public void testMultipleCommitThread() throws Exception {

    final AtomicInteger counter = new AtomicInteger();

    final AbstractFileQueueCommitter committer = new AbstractFileQueueCommitter() {

        @Override/*from   w  w w  . j a  va  2 s .  c  om*/
        protected void commitAddition(IAddOperation operation) throws IOException {
            counter.incrementAndGet();
            operation.delete();
        }

        @Override
        protected void commitDeletion(IDeleteOperation operation) throws IOException {
            counter.incrementAndGet();
            operation.delete();
        }

        @Override
        protected void commitComplete() {
        }
    };

    File queue = temp.newFolder();
    committer.setQueueDir(queue.getPath());
    // Use a bigger number to make sure the files are not 
    // committed while they are added.
    committer.setQueueSize(1000);

    // Queue 50 files for additions
    for (int i = 0; i < 50; i++) {
        Properties metadata = new Properties();
        committer.add(Integer.toString(i), IOUtils.toInputStream("hello world!"), metadata);
    }
    // Queue 50 files for deletions
    for (int i = 50; i < 100; i++) {
        Properties metadata = new Properties();
        committer.remove(Integer.toString(i), metadata);
    }

    ExecutorService pool = Executors.newFixedThreadPool(10);
    for (int i = 0; i < 10; i++) {
        pool.submit(new Runnable() {
            @Override
            public void run() {
                try {
                    committer.commit();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    pool.shutdown();
    pool.awaitTermination(10, TimeUnit.SECONDS);

    // Each file should have been processed exactly once
    assertEquals(100, counter.intValue());

    // All files should have been processed
    Collection<File> files = FileUtils.listFiles(queue, null, true);
    assertTrue(files.isEmpty());
}

From source file:com.cognifide.qa.bb.cumber.BobcumberListener.java

BobcumberListener(Bobcumber bobcumber) {
    this.bobcumber = bobcumber;
    featureMap = new FeatureMap();
    scenarioCounter = new AtomicInteger();
    testFailureCounter = new AtomicInteger();
}

From source file:io.undertow.server.handlers.caching.CacheHandlerTestCase.java

@Test
public void testBasicPathBasedCaching() throws IOException {

    final AtomicInteger responseCount = new AtomicInteger();

    final HttpHandler messageHandler = new HttpHandler() {
        @Override/*from w w  w  . j  a  va 2 s.co  m*/
        public void handleRequest(final HttpServerExchange exchange) throws Exception {
            final ResponseCache cache = exchange.getAttachment(ResponseCache.ATTACHMENT_KEY);
            if (!cache.tryServeResponse()) {
                final String data = "Response " + responseCount.incrementAndGet();
                exchange.getResponseHeaders().put(Headers.CONTENT_LENGTH, data.length() + "");
                exchange.getResponseSender().send(data);
            }
        }
    };
    final CacheHandler cacheHandler = new CacheHandler(new DirectBufferCache(100, 10, 1000), messageHandler);
    DefaultServer.setRootHandler(cacheHandler);

    TestHttpClient client = new TestHttpClient();
    try {
        HttpGet get = new HttpGet(DefaultServer.getDefaultServerURL() + "/path");
        //it takes 5 hits to make an entry actually get cached
        for (int i = 1; i <= 5; ++i) {
            HttpResponse result = client.execute(get);
            Assert.assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode());
            Assert.assertEquals("Response " + i, HttpClientUtils.readResponse(result));
        }

        HttpResponse result = client.execute(get);
        Assert.assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode());
        Assert.assertEquals("Response 5", HttpClientUtils.readResponse(result));

        result = client.execute(get);
        Assert.assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode());
        Assert.assertEquals("Response 5", HttpClientUtils.readResponse(result));

        result = client.execute(get);
        Assert.assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode());
        Assert.assertEquals("Response 5", HttpClientUtils.readResponse(result));

        get = new HttpGet(DefaultServer.getDefaultServerURL() + "/path2");

        result = client.execute(get);
        Assert.assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode());
        Assert.assertEquals("Response 6", HttpClientUtils.readResponse(result));

    } finally {
        client.getConnectionManager().shutdown();
    }
}

From source file:io.fabric8.example.calculator.msg.RequestReplyTest.java

@Test
public void theTest() throws Exception {

    PooledConnectionFactory connectionFactory = new PooledConnectionFactory();
    connectionFactory.setConnectionFactory(new ActiveMQConnectionFactory("failover:(tcp://localhost:61616)"));

    final AtomicInteger counter = new AtomicInteger();
    CamelContext serviceContext = new DefaultCamelContext();
    serviceContext.addComponent("jms", JmsComponent.jmsComponentAutoAcknowledge(connectionFactory));

    serviceContext.addRoutes(new RouteBuilder() {
        @Override/*from ww  w  . java  2s .  co m*/
        public void configure() throws Exception {
            RandomGenerator rg = new JDKRandomGenerator();
            int num = rg.nextInt();
            from("jms:myQueue.queue")
                    // .setHeader("JMSMessageID", constant("ID : " + num))
                    //  .setHeader("JMSReplyTo", constant("myQueue.queue"))
                    .process(new Processor() {
                        @Override
                        public void process(Exchange exchange) throws Exception {
                            String body = exchange.getIn().getBody(String.class);
                            /***
                             * Process data and get the response and set the resposen to the Exchage
                             * body.
                             */
                            exchange.getOut().setBody("RESPONSE " + counter.incrementAndGet());
                        }
                    });
        }
    });
    serviceContext.start();

    CamelContext requestorContext = new DefaultCamelContext();
    requestorContext.addComponent("jms", ActiveMQComponent.jmsComponentAutoAcknowledge(connectionFactory));

    requestorContext.start();

    ProducerTemplate producerTemplate = requestorContext.createProducerTemplate();
    for (int i = 0; i < 1000; i++) {
        Object response = producerTemplate
                .requestBodyAndHeader(
                        "jms:myQueue.queue?exchangePattern=InOut&requestTimeout=40000&timeToLive=40000"
                                + "&asyncConsumer=true&asyncStartListener=true&concurrentConsumers=10"
                                + "&useMessageIDAsCorrelationID=true",
                        "mBodyMsg", "HeaderString", "HeaderValue");

        System.err.println("RESPONSE = " + response);
    }

    requestorContext.stop();
    serviceContext.stop();
}

From source file:com.comcast.viper.flume2storm.connection.sender.EventSenderStats.java

/**
 * Default constructor//from   w ww  . j  a  v  a  2s .c o m
 * 
 * @param eventSenderId
 *          The {@link EventSender} identifier
 */
public EventSenderStats(final String eventSenderId) {
    this.eventSenderId = eventSenderId;
    nbClients = new AtomicInteger();
    nbEventIn = new AtomicLong();
    nbEventOut = new AtomicLong();
    nbEventFailed = new AtomicLong();
}

From source file:com.cloudera.oryx.app.serving.als.model.LoadTestALSModelFactory.java

public static ALSServingModel buildTestModel() {

    log.info("Building load test model...");

    System.gc();/* w  ww .ja v  a  2  s. c  o m*/
    long startMemory = JVMUtils.getUsedMemory();

    ALSServingModel model = new ALSServingModel(FEATURES, true, LSH_SAMPLE_RATE, new TestALSRescorerProvider());
    AtomicLong totalEntries = new AtomicLong();

    int numCores = Runtime.getRuntime().availableProcessors();
    log.info("Adding {} users", USERS);
    AtomicInteger userCount = new AtomicInteger();
    ExecUtils.doInParallel(numCores, i -> {
        RandomGenerator random = RandomManager.getRandom(((long) i << 32) ^ System.nanoTime());
        PoissonDistribution itemPerUserDist = new PoissonDistribution(random, AVG_ITEMS_PER_USER,
                PoissonDistribution.DEFAULT_EPSILON, PoissonDistribution.DEFAULT_MAX_ITERATIONS);
        for (int user = userCount.getAndIncrement(); user < USERS; user = userCount.getAndIncrement()) {
            String userID = "U" + user;
            model.setUserVector(userID, VectorMath.randomVectorF(FEATURES, random));
            int itemsPerUser = itemPerUserDist.sample();
            totalEntries.addAndGet(itemsPerUser);
            Collection<String> knownIDs = new ArrayList<>(itemsPerUser);
            for (int item = 0; item < itemsPerUser; item++) {
                knownIDs.add("I" + random.nextInt(ITEMS));
            }
            model.addKnownItems(userID, knownIDs);
        }
    });

    log.info("Adding {} items", ITEMS);
    AtomicInteger itemCount = new AtomicInteger();
    ExecUtils.doInParallel(numCores, i -> {
        RandomGenerator random = RandomManager.getRandom(((long) i << 32) ^ System.nanoTime());
        for (int item = itemCount.getAndIncrement(); item < ITEMS; item = itemCount.getAndIncrement()) {
            model.setItemVector("I" + item, VectorMath.randomVectorF(FEATURES, random));
        }
    });

    System.gc();
    long endMemory = JVMUtils.getUsedMemory();

    log.info("Built model over {} users, {} items, {} features, {} entries, using {}MB", USERS, ITEMS, FEATURES,
            totalEntries, (endMemory - startMemory) / 1_000_000);
    log.info("Model: {}", model);
    return model;
}