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.msd.gin.halyard.tools.HalyardExportTest.java

private static int getTriplesCount(String uri, String compression, RDFFormat format) throws Exception {
    InputStream in = FileSystem.get(URI.create(uri), HBaseServerTestInstance.getInstanceConfig())
            .open(new Path(uri));
    try {/*from   www. j  av a 2s .co  m*/
        if (compression != null) {
            in = new CompressorStreamFactory().createCompressorInputStream(compression, in);
        }
        RDFParser parser = Rio.createParser(format);
        final AtomicInteger i = new AtomicInteger();
        parser.setRDFHandler(new AbstractRDFHandler() {
            @Override
            public void handleStatement(Statement st) throws RDFHandlerException {
                i.incrementAndGet();
            }
        });
        parser.parse(in, uri);
        return i.get();
    } finally {
        in.close();
    }
}

From source file:io.wcm.caravan.pipeline.impl.JsonPipelineMultipleSubscriptionsTest.java

@SuppressWarnings("unchecked")
@Test/*from ww  w .  j a  v a2  s  .c  o  m*/
public void test3StepPipelineActionCallsReversedOrder() {

    final AtomicInteger subscribeCount = new AtomicInteger();
    initPipelines(subscribeCount);

    Observer<JsonPipelineOutput> firstObserver = Mockito.mock(Observer.class);
    Observer<JsonPipelineOutput> secondObserver = Mockito.mock(Observer.class);
    Observer<JsonPipelineOutput> thirdObserver = Mockito.mock(Observer.class);

    thirdStep.getOutput().subscribe(thirdObserver);
    secondStep.getOutput().subscribe(secondObserver);
    firstStep.getOutput().subscribe(firstObserver);

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

From source file:org.chromium.android_webview.test.AwContentsTest.java

private int callDocumentHasImagesSync(final AwContents awContents) throws Throwable, InterruptedException {
    // Set up a container to hold the result object and a semaphore to
    // make the test wait for the result.
    final AtomicInteger val = new AtomicInteger();
    final Semaphore s = new Semaphore(0);
    final Message msg = Message.obtain(new Handler(Looper.getMainLooper()) {
        @Override//from  ww w . ja  va2 s  . c  o m
        public void handleMessage(Message msg) {
            val.set(msg.arg1);
            s.release();
        }
    });
    runTestOnUiThread(new Runnable() {
        @Override
        public void run() {
            awContents.documentHasImages(msg);
        }
    });
    assertTrue(s.tryAcquire(WAIT_TIMEOUT_MS, TimeUnit.MILLISECONDS));
    int result = val.get();
    return result;
}

From source file:com.btoddb.chronicle.plunkers.HdfsPlunkerImplIT.java

@Test
@Ignore("very flakey, need to work out a more stable way of testing")
public void testLongRun() throws Exception {
    plunker.setIdleTimeout(0);//from   www.  j  av  a 2 s . c  o m
    plunker.setRollPeriod(2);
    plunker.setTimeoutCheckPeriod(100);
    plunker.init(config);

    final int sleep = 200;
    final int maxCount = 100; // 20 seconds at 'sleep' interval should be 10 files
    final AtomicInteger count = new AtomicInteger();

    // do this to prime HDFS FileSystem object - otherwise timing is off
    plunker.handleInternal(Arrays.asList(new Event("the-body").withHeader("customer", "cust")
            .withHeader("msgId", String.valueOf(count.getAndIncrement()))));

    ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
    System.out.println("start");
    executor.scheduleWithFixedDelay(new Runnable() {
        @Override
        public void run() {
            try {
                System.out.println("time = " + System.currentTimeMillis());
                plunker.handleInternal(Arrays.asList(new Event("the-body").withHeader("customer", "cust")
                        .withHeader("msgId", String.valueOf(count.get()))));
            } catch (Exception e) {
                e.printStackTrace();
            }

            count.incrementAndGet();
        }
    }, 0, sleep, TimeUnit.MILLISECONDS);

    while (count.get() < maxCount) {
        Thread.sleep(sleep / 2);
    }

    executor.shutdown();
    executor.awaitTermination(60, TimeUnit.SECONDS);

    Thread.sleep(1500);

    plunker.shutdown();

    Event[] events = new Event[count.get()];
    for (int i = 0; i < count.get(); i++) {
        events[i] = new Event("the-body").withHeader("customer", "cust").withHeader("msgId", String.valueOf(i));
    }

    File theDir = new File(String.format("%s/the/cust/path", baseDir.getPath()));

    assertThat(theDir, ftUtils.countWithSuffix(".tmp", 0));
    assertThat(theDir, ftUtils.countWithSuffix(".avro", 10));

    assertThat(theDir, ftUtils.hasEventsInDir(events));
}

From source file:net.centro.rtb.monitoringcenter.metrics.tomcat.TomcatConnectorMetricSet.java

TomcatConnectorMetricSet(ObjectName threadPoolObjectName) {
    Preconditions.checkNotNull(threadPoolObjectName);

    MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer();

    this.name = threadPoolObjectName.getKeyProperty("name");
    this.port = JmxUtil.getJmxAttribute(threadPoolObjectName, "port", Integer.class, null);

    Set<ObjectName> connectorObjectNames = null;
    try {//from w w w  .j  a v a2s.c  o  m
        connectorObjectNames = mBeanServer.queryNames(new ObjectName("Catalina:type=Connector,port=" + port),
                null);
    } catch (MalformedObjectNameException e) {
        logger.debug("Invalid ObjectName defined for the Tomcat's Connector MxBean for the {} thread pool",
                name, e);
    }

    if (connectorObjectNames != null && !connectorObjectNames.isEmpty()) {
        ObjectName connectorObjectName = connectorObjectNames.iterator().next();
        String internalPortStr = JmxUtil.getJmxAttribute(connectorObjectName, "internalPort", String.class,
                Boolean.FALSE.toString());
        this.isInternalPort = Boolean.TRUE.toString().equalsIgnoreCase(internalPortStr);
    }

    this.isSecure = JmxUtil.getJmxAttribute(threadPoolObjectName, "sSLEnabled", Boolean.class, Boolean.FALSE);
    this.isAjp = isAjpFromName(name);

    Map<String, Metric> metricsByNames = new HashMap<>();

    this.currentPoolSizeGauge = JmxUtil.getJmxAttributeAsGauge(threadPoolObjectName, "currentThreadCount",
            Integer.class, 0);
    if (currentPoolSizeGauge != null) {
        metricsByNames.put("currentPoolSize", currentPoolSizeGauge);
    }

    this.maxPoolSizeGauge = JmxUtil.getJmxAttributeAsGauge(threadPoolObjectName, "maxThreads", Integer.class,
            0);
    if (maxPoolSizeGauge != null) {
        metricsByNames.put("maxPoolSize", maxPoolSizeGauge);
    }

    this.busyThreadsGauge = JmxUtil.getJmxAttributeAsGauge(threadPoolObjectName, "currentThreadsBusy",
            Integer.class, 0);
    if (busyThreadsGauge != null) {
        metricsByNames.put("busyThreads", busyThreadsGauge);
    }

    this.activeConnectionsGauge = JmxUtil.getJmxAttributeAsGauge(threadPoolObjectName, "connectionCount",
            Long.class, 0L);
    if (activeConnectionsGauge != null) {
        metricsByNames.put("activeConnections", activeConnectionsGauge);
    }

    this.maxConnectionsGauge = JmxUtil.getJmxAttributeAsGauge(threadPoolObjectName, "maxConnections",
            Integer.class, 0);
    if (maxConnectionsGauge != null) {
        metricsByNames.put("maxConnections", maxConnectionsGauge);
    }

    Set<ObjectName> globalRequestProcessorObjectNames = null;
    try {
        globalRequestProcessorObjectNames = mBeanServer
                .queryNames(new ObjectName("Catalina:type=GlobalRequestProcessor,name=" + name), null);
    } catch (MalformedObjectNameException e) {
        logger.debug(
                "Invalid ObjectName defined for the Tomcat's GlobalRequestProcessor MxBean for the {} thread pool",
                name, e);
    }

    if (globalRequestProcessorObjectNames != null && !globalRequestProcessorObjectNames.isEmpty()) {
        ObjectName globalRequestProcessorObjectName = globalRequestProcessorObjectNames.iterator().next();
        this.totalRequestsGauge = JmxUtil.getJmxAttributeAsGauge(globalRequestProcessorObjectName,
                "requestCount", Integer.class, 0);

        if (totalRequestsGauge != null) {
            metricsByNames.put("totalRequests", totalRequestsGauge);

            this.qpsHolder = new AtomicInteger();
            this.previousRequestCount = totalRequestsGauge.getValue();

            this.qpsGauge = new Gauge<Integer>() {
                @Override
                public Integer getValue() {
                    return qpsHolder.get();
                }
            };
            metricsByNames.put("qps", qpsGauge);
        }

        this.errorsGauge = JmxUtil.getJmxAttributeAsGauge(globalRequestProcessorObjectName, "errorCount",
                Integer.class, 0);
        if (errorsGauge != null) {
            metricsByNames.put("errors", errorsGauge);
        }

        this.receivedBytesGauge = JmxUtil.getJmxAttributeAsGauge(globalRequestProcessorObjectName,
                "bytesReceived", Long.class, 0L);
        if (receivedBytesGauge != null) {
            metricsByNames.put("receivedBytes", receivedBytesGauge);
        }

        this.sentBytesGauge = JmxUtil.getJmxAttributeAsGauge(globalRequestProcessorObjectName, "bytesSent",
                Long.class, 0L);
        if (sentBytesGauge != null) {
            metricsByNames.put("sentBytes", sentBytesGauge);
        }
    }

    this.metricsByNames = metricsByNames;
}

From source file:metlos.executors.batch.BatchExecutorTest.java

public void testChangesInTaskCollectionPickedUpInRepetitions() throws Exception {
    final ConcurrentLinkedQueue<Runnable> tasks = new ConcurrentLinkedQueue<Runnable>();
    final AtomicInteger reportedNofTasks = new AtomicInteger();
    final CountDownLatch waitForTask2 = new CountDownLatch(2);
    final CountDownLatch waitForTask3 = new CountDownLatch(2);

    Runnable task1 = new Runnable() {
        @Override//  www .j a v  a2s.com
        public void run() {
        }
    };

    Runnable task2 = new Runnable() {
        @Override
        public void run() {
            if (tasks.size() == 2) {
                reportedNofTasks.set(2);
                waitForTask2.countDown();
            }
        }
    };

    Runnable task3 = new Runnable() {
        @Override
        public void run() {
            if (tasks.size() == 3) {
                reportedNofTasks.set(3);
                waitForTask3.countDown();
            }
        }
    };

    BatchExecutor ex = getExecutor(10);

    tasks.add(task1);
    tasks.add(task2);

    ex.submitWithPreferedDurationAndFixedDelay(tasks, 0, 0, 0, TimeUnit.MILLISECONDS);

    //k, now the tasks should be running and there should be just 2 of them...
    //so we should be getting the value of "2" reported by the reportedNofTasks

    waitForTask2.countDown();
    waitForTask2.await();

    int currentReportedTasks = reportedNofTasks.get();

    assert currentReportedTasks == 2 : "We should be getting 2 tasks reported but are getting "
            + currentReportedTasks + " instead.";

    //k, now let's try updating the tasks collection... this should get picked up by the
    //repeated executions 
    tasks.add(task3);

    //now the reported nof tasks should change to 3. let's wait on it first to make sure the executor has had time to 
    //register the change.        
    waitForTask3.countDown();
    waitForTask3.await();

    currentReportedTasks = reportedNofTasks.get();

    assert currentReportedTasks == 3 : "We should be getting 3 tasks reported but are getting "
            + currentReportedTasks + " instead.";

    ex.shutdown();
}

From source file:com.github.brandtg.switchboard.TestMysqlLogServer.java

@Test
public void testMysqlEventListener() throws Exception {
    try (Connection conn = DriverManager.getConnection(jdbc, "root", "")) {
        // Write some rows, so we have binlog entries
        PreparedStatement pstmt = conn.prepareStatement("INSERT INTO simple VALUES(?, ?)");
        for (int i = 0; i < 10; i++) {
            pstmt.setInt(1, i);//from   www . j a v  a 2  s  .co m
            pstmt.setInt(2, i);
            pstmt.execute();
        }
    }

    final AtomicInteger insertCount = new AtomicInteger();
    final AtomicInteger beginCount = new AtomicInteger();
    final AtomicInteger commitCount = new AtomicInteger();
    final AtomicInteger rollbackCount = new AtomicInteger();
    InetSocketAddress sourceAddress = new InetSocketAddress(8080);
    InetSocketAddress sinkAddress = new InetSocketAddress(9090);
    MysqlEventListener eventListener = new MysqlEventListener("test", sourceAddress, sinkAddress) {
        @Override
        public void onBegin(UUID sourceId, long transactionId) {
            beginCount.incrementAndGet();
        }

        @Override
        public void onInsert(List<Row> rows) {
            insertCount.incrementAndGet();
        }

        @Override
        public void onUpdate(List<Pair<Row>> rows) {

        }

        @Override
        public void onDelete(List<Row> rows) {

        }

        @Override
        public void onCommit() {
            commitCount.incrementAndGet();
        }

        @Override
        public void onRollback() {
            rollbackCount.incrementAndGet();
        }
    };

    try {
        eventListener.start();

        long startTime = System.currentTimeMillis();
        long currentTime = startTime;
        do {
            // Once we've seen all writes, check expected state
            if (insertCount.get() == 10) {
                Assert.assertEquals(beginCount.get(), 10);
                Assert.assertEquals(commitCount.get(), 10);
                Assert.assertEquals(rollbackCount.get(), 0);
                return;
            }
            Thread.sleep(pollMillis);
            currentTime = System.currentTimeMillis();
        } while (currentTime - startTime < timeoutMillis);
    } finally {
        eventListener.shutdown();
    }

    Assert.fail("Timed out while polling");
}

From source file:com.nearinfinity.blur.thrift.AsyncClientPool.java

private TAsyncClient newClient(Class<?> c, Connection connection) throws InterruptedException {
    BlockingQueue<TAsyncClient> blockingQueue = getQueue(connection);
    TAsyncClient client = blockingQueue.poll();
    if (client != null) {
        return client;
    }/*from  ww w .  j a  va 2  s. co m*/

    AtomicInteger counter;
    synchronized (_numberOfConnections) {
        counter = _numberOfConnections.get(connection.getHost());
        if (counter == null) {
            counter = new AtomicInteger();
            _numberOfConnections.put(connection.getHost(), counter);
        }
    }

    synchronized (counter) {
        int numOfConnections = counter.get();
        while (numOfConnections >= _maxConnectionsPerHost) {
            client = blockingQueue.poll(_pollTime, TimeUnit.MILLISECONDS);
            if (client != null) {
                return client;
            }
            LOG.debug("Waiting for client number of connection [" + numOfConnections
                    + "], max connection per host [" + _maxConnectionsPerHost + "]");
            numOfConnections = counter.get();
        }
        LOG.info("Creating a new client for [" + connection + "]");
        String name = c.getName();
        Constructor<?> constructor = _constructorCache.get(name);
        if (constructor == null) {
            String clientClassName = name.replace("$AsyncIface", "$AsyncClient");
            try {
                Class<?> clazz = Class.forName(clientClassName);
                constructor = clazz.getConstructor(new Class[] { TProtocolFactory.class,
                        TAsyncClientManager.class, TNonblockingTransport.class });
                _constructorCache.put(name, constructor);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
        try {
            TNonblockingSocket transport = newTransport(connection);
            client = (TAsyncClient) constructor
                    .newInstance(new Object[] { _protocolFactory, _clientManager, transport });
            client.setTimeout(_timeout);
            counter.incrementAndGet();
            return client;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}

From source file:com.brsanthu.dataexporter.DataWriter.java

public void finishExporting() {
    rowIndex = new AtomicInteger();
}