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

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

Introduction

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

Prototype

public final int get() 

Source Link

Document

Returns the current value, with memory effects as specified by VarHandle#getVolatile .

Usage

From source file:com.spectralogic.ds3client.integration.GetJobManagement_Test.java

@Test
public void testFiringFailureHandlerWhenGettingObject() throws URISyntaxException, NoSuchMethodException,
        InvocationTargetException, IllegalAccessException, IOException {
    final String tempPathPrefix = null;
    final Path tempDirectory = Files.createTempDirectory(Paths.get("."), tempPathPrefix);

    try {/*from www  . jav a2s . c  om*/
        final AtomicInteger numFailuresRecorded = new AtomicInteger();

        final FailureEventListener failureEventListener = new FailureEventListener() {
            @Override
            public void onFailure(final FailureEvent failureEvent) {
                numFailuresRecorded.incrementAndGet();
                assertEquals(FailureEvent.FailureActivity.GettingObject, failureEvent.doingWhat());
            }
        };

        final Ds3ClientHelpers.Job readJob = createReadJobWithObjectsReadyToTransfer(
                Ds3ClientShimFactory.ClientFailureType.GetObject);

        readJob.attachFailureEventListener(failureEventListener);

        try {
            readJob.transfer(new FileObjectGetter(tempDirectory));
        } catch (final IOException e) {
            assertEquals(1, numFailuresRecorded.get());
        }
    } finally {
        FileUtils.deleteDirectory(tempDirectory.toFile());
    }
}

From source file:com.btoddb.fastpersitentqueue.flume.FpqChannelTest.java

@Test
public void testThreading() throws Exception {
    final int numEntries = 1000;
    final int numPushers = 4;
    final int numPoppers = 4;
    final int entrySize = 1000;
    channel.setMaxTransactionSize(2000);
    final int popBatchSize = 100;
    channel.setMaxMemorySegmentSizeInBytes(10000000);
    channel.setMaxJournalFileSize(10000000);
    channel.setMaxJournalDurationInMs(30000);
    channel.setFlushPeriodInMs(1000);/* w w w  .  ja  v  a 2s .c o  m*/
    channel.setNumberOfFlushWorkers(4);

    final Random pushRand = new Random(1000L);
    final Random popRand = new Random(1000000L);
    final AtomicInteger pusherFinishCount = new AtomicInteger();
    final AtomicInteger numPops = new AtomicInteger();
    final AtomicLong counter = new AtomicLong();
    final AtomicLong pushSum = new AtomicLong();
    final AtomicLong popSum = new AtomicLong();

    channel.start();

    ExecutorService execSrvc = Executors.newFixedThreadPool(numPushers + numPoppers);

    Set<Future> futures = new HashSet<Future>();

    // start pushing
    for (int i = 0; i < numPushers; i++) {
        Future future = execSrvc.submit(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < numEntries; i++) {
                    try {
                        long x = counter.getAndIncrement();
                        pushSum.addAndGet(x);
                        ByteBuffer bb = ByteBuffer.wrap(new byte[entrySize]);
                        bb.putLong(x);

                        Transaction tx = channel.getTransaction();
                        tx.begin();
                        MyEvent event1 = new MyEvent();
                        event1.addHeader("x", String.valueOf(x)).setBody(new byte[numEntries - 8]); // take out size of long
                        channel.put(event1);
                        tx.commit();
                        tx.close();

                        Thread.sleep(pushRand.nextInt(5));
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                pusherFinishCount.incrementAndGet();
            }
        });
        futures.add(future);
    }

    // start popping
    for (int i = 0; i < numPoppers; i++) {
        Future future = execSrvc.submit(new Runnable() {
            @Override
            public void run() {
                while (pusherFinishCount.get() < numPushers || !channel.isEmpty()) {
                    try {
                        Transaction tx = channel.getTransaction();
                        tx.begin();

                        Event event;
                        int count = popBatchSize;
                        while (null != (event = channel.take()) && count-- > 0) {
                            popSum.addAndGet(Long.valueOf(event.getHeaders().get("x")));
                            numPops.incrementAndGet();
                        }

                        tx.commit();
                        tx.close();

                        Thread.sleep(popRand.nextInt(10));
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        });
        futures.add(future);
    }

    boolean finished = false;
    while (!finished) {
        try {
            for (Future f : futures) {
                f.get();
            }
            finished = true;
        } catch (InterruptedException e) {
            // ignore
            Thread.interrupted();
        }
    }

    assertThat(numPops.get(), is(numEntries * numPushers));
    assertThat(channel.isEmpty(), is(true));
    assertThat(pushSum.get(), is(popSum.get()));
}

From source file:com.spectralogic.ds3client.integration.GetJobManagement_Test.java

@Test
public void testFiringFailureHandlerWhenGettingChunks() throws URISyntaxException, NoSuchMethodException,
        InvocationTargetException, IllegalAccessException, IOException {
    final String tempPathPrefix = null;
    final Path tempDirectory = Files.createTempDirectory(Paths.get("."), tempPathPrefix);

    try {/*w  ww. ja  v  a 2 s .  c o  m*/
        final AtomicInteger numFailuresRecorded = new AtomicInteger();

        final FailureEventListener failureEventListener = new FailureEventListener() {
            @Override
            public void onFailure(final FailureEvent failureEvent) {
                numFailuresRecorded.incrementAndGet();
                assertEquals(FailureEvent.FailureActivity.GettingObject, failureEvent.doingWhat());
            }
        };

        final Ds3ClientHelpers.Job readJob = createReadJobWithObjectsReadyToTransfer(
                Ds3ClientShimFactory.ClientFailureType.ChunkAllocation);

        readJob.attachFailureEventListener(failureEventListener);

        try {
            readJob.transfer(new FileObjectGetter(tempDirectory));
        } catch (final IOException e) {
            assertEquals(1, numFailuresRecorded.get());
        }
    } finally {
        FileUtils.deleteDirectory(tempDirectory.toFile());
    }
}

From source file:org.dasein.cloud.azure.tests.network.AzureIpAddressSupportTest.java

@Test
public void stopForwardToServerShouldPostCorrectRequestIfNoMatchEndpointFound()
        throws CloudException, InternalException {
    final AtomicInteger putCount = new AtomicInteger(0);
    new MockUp<CloseableHttpClient>() {
        @Mock(invocations = 2)//from www.ja  v a2 s  .  c  om
        public CloseableHttpResponse execute(Invocation inv, HttpUriRequest request) throws IOException {
            if (request.getMethod().equals("GET")) {
                DaseinObjectToXmlEntity<PersistentVMRoleModel> daseinEntity = new DaseinObjectToXmlEntity<PersistentVMRoleModel>(
                        createPersistentVMRoleModelWithEndpoint());
                assertGet(request, EXPECTED_URL,
                        new Header[] { new BasicHeader("x-ms-version", "2012-03-01") });
                return getHttpResponseMock(getStatusLineMock(HttpServletResponse.SC_OK), daseinEntity,
                        new Header[] { new BasicHeader("x-ms-request-id", UUID.randomUUID().toString()) });
            } else if (request.getMethod().equals("PUT")) {
                putCount.incrementAndGet();
                PersistentVMRoleModel persistentVMRoleModel = createPersistentVMRoleModelWithEndpoint();
                assertPut(request, EXPECTED_URL, new Header[] { new BasicHeader("x-ms-version", "2012-03-01") },
                        persistentVMRoleModel);
                return getHttpResponseMock(getStatusLineMock(HttpServletResponse.SC_ACCEPTED), null,
                        new Header[] { new BasicHeader("x-ms-request-id", UUID.randomUUID().toString()) });
            } else {
                throw new IOException("Request is not mocked");
            }
        }
    };
    String ruleId = new AzureRuleIdParts(VM_ID, Protocol.TCP.toString(), String.valueOf(PRIVATE_PORT + 1))
            .toProviderId();
    ipAddressSupport.stopForwardToServer(ruleId, VM_ID);
    assertEquals("PUT count doesn't match", 1, putCount.get());
}

From source file:org.apache.directory.studio.test.integration.ui.BrowserTest.java

/**
 * Test for DIRSTUDIO-1121./*w ww  .j  a va  2  s  .  c om*/
 *
 * Verify input is set only once when entry is selected.
 */
@Test
public void testSetInputOnlyOnce() throws Exception {
    browserViewBot.selectEntry("DIT", "Root DSE", "ou=system", "ou=users");
    browserViewBot.expandEntry("DIT", "Root DSE", "ou=system", "ou=users");

    // verify link-with-editor is enabled
    assertTrue(BrowserUIPlugin.getDefault().getPreferenceStore()
            .getBoolean(BrowserUIConstants.PREFERENCE_BROWSER_LINK_WITH_EDITOR));

    // setup counter and listener to record entry editor input changes
    final AtomicInteger counter = new AtomicInteger();
    UIThreadRunnable.syncExec(new VoidResult() {
        public void run() {
            try {
                IEditorPart editor = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage()
                        .getActiveEditor();
                editor.addPropertyListener(new IPropertyListener() {
                    @Override
                    public void propertyChanged(Object source, int propId) {
                        if (source instanceof EntryEditor && propId == BrowserUIConstants.INPUT_CHANGED) {
                            counter.incrementAndGet();
                        }
                    }
                });
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
    });

    // select 3 different entries, select one twice should not set the input again
    browserViewBot.selectEntry("DIT", "Root DSE", "ou=system", "ou=users", "uid=user.1");
    browserViewBot.selectEntry("DIT", "Root DSE", "ou=system", "ou=users", "uid=user.1");
    browserViewBot.selectEntry("DIT", "Root DSE", "ou=system", "ou=users", "uid=user.2");
    browserViewBot.selectEntry("DIT", "Root DSE", "ou=system", "ou=users", "uid=user.2");
    browserViewBot.selectEntry("DIT", "Root DSE", "ou=system", "ou=users", "uid=user.3");
    browserViewBot.selectEntry("DIT", "Root DSE", "ou=system", "ou=users", "uid=user.3");

    // verify that input was only set 3 times.
    assertEquals("Only 3 input changes expected.", 3, counter.get());

    // reset counter
    counter.set(0);

    // use navigation history to go back and forth, each step should set input only once
    studioBot.navigationHistoryBack();
    browserViewBot.waitUntilEntryIsSelected("uid=user.2");
    studioBot.navigationHistoryBack();
    browserViewBot.waitUntilEntryIsSelected("uid=user.1");
    studioBot.navigationHistoryForward();
    browserViewBot.waitUntilEntryIsSelected("uid=user.2");
    studioBot.navigationHistoryForward();
    browserViewBot.waitUntilEntryIsSelected("uid=user.3");

    // verify that input was only set 4 times.
    assertEquals("Only 4 input changes expected.", 4, counter.get());
}

From source file:org.apache.hadoop.hbase.client.TestAdmin1.java

void splitTest(byte[] splitPoint, byte[][] familyNames, int[] rowCounts, int numVersions, int blockSize)
        throws Exception {
    TableName tableName = TableName.valueOf("testForceSplit");
    StringBuilder sb = new StringBuilder();
    // Add tail to String so can see better in logs where a test is running.
    for (int i = 0; i < rowCounts.length; i++) {
        sb.append("_").append(Integer.toString(rowCounts[i]));
    }/*w ww  .ja v a2 s  .co m*/
    assertFalse(admin.tableExists(tableName));
    try (final Table table = TEST_UTIL.createTable(tableName, familyNames, numVersions, blockSize);
            final RegionLocator locator = TEST_UTIL.getConnection().getRegionLocator(tableName)) {

        int rowCount = 0;
        byte[] q = new byte[0];

        // insert rows into column families. The number of rows that have values
        // in a specific column family is decided by rowCounts[familyIndex]
        for (int index = 0; index < familyNames.length; index++) {
            ArrayList<Put> puts = new ArrayList<Put>(rowCounts[index]);
            for (int i = 0; i < rowCounts[index]; i++) {
                byte[] k = Bytes.toBytes(i);
                Put put = new Put(k);
                put.addColumn(familyNames[index], q, k);
                puts.add(put);
            }
            table.put(puts);

            if (rowCount < rowCounts[index]) {
                rowCount = rowCounts[index];
            }
        }

        // get the initial layout (should just be one region)
        List<HRegionLocation> m = locator.getAllRegionLocations();
        LOG.info("Initial regions (" + m.size() + "): " + m);
        assertTrue(m.size() == 1);

        // Verify row count
        Scan scan = new Scan();
        ResultScanner scanner = table.getScanner(scan);
        int rows = 0;
        for (@SuppressWarnings("unused")
        Result result : scanner) {
            rows++;
        }
        scanner.close();
        assertEquals(rowCount, rows);

        // Have an outstanding scan going on to make sure we can scan over splits.
        scan = new Scan();
        scanner = table.getScanner(scan);
        // Scan first row so we are into first region before split happens.
        scanner.next();

        // Split the table
        this.admin.split(tableName, splitPoint);

        final AtomicInteger count = new AtomicInteger(0);
        Thread t = new Thread("CheckForSplit") {
            @Override
            public void run() {
                for (int i = 0; i < 45; i++) {
                    try {
                        sleep(1000);
                    } catch (InterruptedException e) {
                        continue;
                    }
                    // check again
                    List<HRegionLocation> regions = null;
                    try {
                        regions = locator.getAllRegionLocations();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    if (regions == null)
                        continue;
                    count.set(regions.size());
                    if (count.get() >= 2) {
                        LOG.info("Found: " + regions);
                        break;
                    }
                    LOG.debug("Cycle waiting on split");
                }
                LOG.debug("CheckForSplit thread exited, current region count: " + count.get());
            }
        };
        t.setPriority(Thread.NORM_PRIORITY - 2);
        t.start();
        t.join();

        // Verify row count
        rows = 1; // We counted one row above.
        for (@SuppressWarnings("unused")
        Result result : scanner) {
            rows++;
            if (rows > rowCount) {
                scanner.close();
                assertTrue("Scanned more than expected (" + rowCount + ")", false);
            }
        }
        scanner.close();
        assertEquals(rowCount, rows);

        List<HRegionLocation> regions = null;
        try {
            regions = locator.getAllRegionLocations();
        } catch (IOException e) {
            e.printStackTrace();
        }
        assertEquals(2, regions.size());
        if (splitPoint != null) {
            // make sure the split point matches our explicit configuration
            assertEquals(Bytes.toString(splitPoint),
                    Bytes.toString(regions.get(0).getRegionInfo().getEndKey()));
            assertEquals(Bytes.toString(splitPoint),
                    Bytes.toString(regions.get(1).getRegionInfo().getStartKey()));
            LOG.debug("Properly split on " + Bytes.toString(splitPoint));
        } else {
            if (familyNames.length > 1) {
                int splitKey = Bytes.toInt(regions.get(0).getRegionInfo().getEndKey());
                // check if splitKey is based on the largest column family
                // in terms of it store size
                int deltaForLargestFamily = Math.abs(rowCount / 2 - splitKey);
                LOG.debug("SplitKey=" + splitKey + "&deltaForLargestFamily=" + deltaForLargestFamily + ", r="
                        + regions.get(0).getRegionInfo());
                for (int index = 0; index < familyNames.length; index++) {
                    int delta = Math.abs(rowCounts[index] / 2 - splitKey);
                    if (delta < deltaForLargestFamily) {
                        assertTrue("Delta " + delta + " for family " + index + " should be at least "
                                + "deltaForLargestFamily " + deltaForLargestFamily, false);
                    }
                }
            }
        }
        TEST_UTIL.deleteTable(tableName);
    }
}

From source file:com.yahoo.pulsar.broker.service.PersistentQueueE2ETest.java

@Test
public void testConsumersWithDifferentPermits() throws Exception {
    final String topicName = "persistent://prop/use/ns-abc/shared-topic4";
    final String subName = "sub4";
    final int numMsgs = 10000;

    final AtomicInteger msgCountConsumer1 = new AtomicInteger(0);
    final AtomicInteger msgCountConsumer2 = new AtomicInteger(0);
    final CountDownLatch latch = new CountDownLatch(numMsgs);

    int recvQ1 = 10;
    ConsumerConfiguration conf1 = new ConsumerConfiguration();
    conf1.setSubscriptionType(SubscriptionType.Shared);
    conf1.setReceiverQueueSize(recvQ1);/*from  w ww  . jav a2 s.  c o  m*/
    conf1.setMessageListener((consumer, msg) -> {
        msgCountConsumer1.incrementAndGet();
        try {
            consumer.acknowledge(msg);
            latch.countDown();
        } catch (PulsarClientException e) {
            fail("Should not fail");
        }
    });

    int recvQ2 = 1;
    ConsumerConfiguration conf2 = new ConsumerConfiguration();
    conf2.setSubscriptionType(SubscriptionType.Shared);
    conf2.setReceiverQueueSize(recvQ2);
    conf2.setMessageListener((consumer, msg) -> {
        msgCountConsumer2.incrementAndGet();
        try {
            consumer.acknowledge(msg);
            latch.countDown();
        } catch (PulsarClientException e) {
            fail("Should not fail");
        }
    });

    Consumer consumer1 = pulsarClient.subscribe(topicName, subName, conf1);
    Consumer consumer2 = pulsarClient.subscribe(topicName, subName, conf2);

    List<CompletableFuture<MessageId>> futures = Lists.newArrayListWithCapacity(numMsgs);
    Producer producer = pulsarClient.createProducer(topicName);
    for (int i = 0; i < numMsgs; i++) {
        String message = "msg-" + i;
        futures.add(producer.sendAsync(message.getBytes()));
    }
    FutureUtil.waitForAll(futures).get();
    producer.close();

    latch.await(5, TimeUnit.SECONDS);

    assertEquals(msgCountConsumer1.get(), numMsgs - numMsgs / (recvQ1 + recvQ2), numMsgs * 0.1);
    assertEquals(msgCountConsumer2.get(), numMsgs / (recvQ1 + recvQ2), numMsgs * 0.1);

    consumer1.close();
    consumer2.close();
    admin.persistentTopics().delete(topicName);
}

From source file:com.couchbase.client.core.endpoint.query.QueryHandlerTest.java

@Test
public void shouldDecodeOneRowResponseWithNoClientID() throws Exception {
    String response = Resources.read("no_client_id.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));

    GenericQueryRequest requestMock = mock(GenericQueryRequest.class);
    queue.add(requestMock);/*from   w  w w  .j a v  a 2  s.c o  m*/
    channel.writeInbound(responseHeader, responseChunk);
    latch.await(1, TimeUnit.SECONDS);
    assertEquals(1, firedEvents.size());
    GenericQueryResponse inbound = (GenericQueryResponse) firedEvents.get(0);

    final AtomicInteger invokeCounter1 = new AtomicInteger();
    assertResponse(inbound, true, ResponseStatus.SUCCESS, FAKE_REQUESTID, "", "success", FAKE_SIGNATURE,
            new Action1<ByteBuf>() {
                @Override
                public void call(ByteBuf buf) {
                    invokeCounter1.incrementAndGet();
                    String response = buf.toString(CharsetUtil.UTF_8);
                    try {
                        Map found = mapper.readValue(response, Map.class);
                        assertEquals(12, found.size());
                        assertEquals("San Francisco", found.get("city"));
                        assertEquals("United States", found.get("country"));
                        Map geo = (Map) found.get("geo");
                        assertNotNull(geo);
                        assertEquals(3, geo.size());
                        assertEquals("ROOFTOP", geo.get("accuracy"));
                    } catch (IOException e) {
                        assertFalse(true);
                    }
                }
            }, new Action1<ByteBuf>() {
                @Override
                public void call(ByteBuf buf) {
                    fail("no error expected");
                }
            }, expectedMetricsCounts(0, 1));
    assertEquals(1, invokeCounter1.get());
}

From source file:com.spectralogic.ds3client.integration.Smoke_Test.java

@Test
public void eventHandlerRegistrationAndDeregistration()
        throws IOException, URISyntaxException, XmlProcessingException {
    final String bucketName = "eventBucket";

    try {//from  w  w w. j  av a2  s . c  om
        final AtomicInteger counter = new AtomicInteger(0);

        HELPERS.ensureBucketExists(bucketName, envDataPolicyId);

        loadBookTestData(client, bucketName);

        final List<Ds3Object> objs = Lists.newArrayList(new Ds3Object("beowulf.txt"));

        final Ds3ClientHelpers.Job job = HELPERS.startReadJob(bucketName, objs);

        final ObjectCompletedListener eventHandler = new ObjectCompletedListener() {
            @Override
            public void objectCompleted(final String name) {
                LOG.info("finished getting: " + name);
                counter.incrementAndGet();
            }
        };

        job.attachObjectCompletedListener(eventHandler);

        job.removeObjectCompletedListener(eventHandler);

        job.transfer(new Ds3ClientHelpers.ObjectChannelBuilder() {
            @Override
            public SeekableByteChannel buildChannel(final String key) throws IOException {
                return new NullChannel();
            }
        });

        assertThat(counter.get(), is(0));
    } finally {
        deleteAllContents(client, bucketName);
    }
}

From source file:com.couchbase.client.core.endpoint.query.QueryHandlerTest.java

@Test
public void shouldDecodeOneRowResponseWithShortClientID() throws Exception {
    String response = Resources.read("short_client_id.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));

    GenericQueryRequest requestMock = mock(GenericQueryRequest.class);
    queue.add(requestMock);//from   w w w  .  j ava2  s . c o  m
    channel.writeInbound(responseHeader, responseChunk);
    latch.await(1, TimeUnit.SECONDS);
    assertEquals(1, firedEvents.size());
    GenericQueryResponse inbound = (GenericQueryResponse) firedEvents.get(0);

    final AtomicInteger invokeCounter1 = new AtomicInteger();
    assertResponse(inbound, true, ResponseStatus.SUCCESS, FAKE_REQUESTID, "123456789", "success",
            FAKE_SIGNATURE, new Action1<ByteBuf>() {
                @Override
                public void call(ByteBuf buf) {
                    invokeCounter1.incrementAndGet();
                    String response = buf.toString(CharsetUtil.UTF_8);
                    try {
                        Map found = mapper.readValue(response, Map.class);
                        assertEquals(12, found.size());
                        assertEquals("San Francisco", found.get("city"));
                        assertEquals("United States", found.get("country"));
                        Map geo = (Map) found.get("geo");
                        assertNotNull(geo);
                        assertEquals(3, geo.size());
                        assertEquals("ROOFTOP", geo.get("accuracy"));
                    } catch (IOException e) {
                        assertFalse(true);
                    }
                }
            }, new Action1<ByteBuf>() {
                @Override
                public void call(ByteBuf buf) {
                    fail("no error expected");
                }
            }, expectedMetricsCounts(0, 1));
    assertEquals(1, invokeCounter1.get());
}