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:org.fcrepo.client.ConnectionManagementTest.java

/**
 * Demonstrates that are connections are released when the user of the FcrepoClient reads the HTTP entity body.
 *//*from w  w w.  j  av  a2s.com*/
@Test
public void connectionReleasedOnEntityBodyRead() {
    final int expectedCount = (int) Stream.of(HttpMethods.values()).filter(m -> m.entity).count();
    final AtomicInteger actualCount = new AtomicInteger(0);
    final MockHttpExpectations.Uris uri = uris.uri200;

    Stream.of(HttpMethods.values()).filter(method -> method.entity).forEach(method -> {
        connect(client, uri, method, FcrepoResponseHandler.readEntityBody);
        actualCount.getAndIncrement();
    });

    assertEquals("Expected to make " + expectedCount + " connections; made " + actualCount.get(), expectedCount,
            actualCount.get());
    verifyConnectionRequestedAndClosed(actualCount.get(), connectionManager);
}

From source file:org.fcrepo.client.ConnectionManagementTest.java

/**
 * Demonstrates that HTTP connections are released when the user of the FcrepoClient closes the HTTP entity body.
 * Each method of the FcrepoClient (get, put, post, etc.) is tested.
 *///from   w w w .j  a v a  2 s  . c o  m
@Test
public void connectionReleasedOnEntityBodyClose() {
    final int expectedCount = (int) Stream.of(HttpMethods.values()).filter(m -> m.entity).count();
    final AtomicInteger actualCount = new AtomicInteger(0);
    final MockHttpExpectations.Uris uri = uris.uri200;

    Stream.of(HttpMethods.values()).filter(method -> method.entity).forEach(method -> {
        connect(client, uri, method, FcrepoResponseHandler.closeEntityBody);
        actualCount.getAndIncrement();
    });

    assertEquals("Expected to make " + expectedCount + " connections; made " + actualCount.get(), expectedCount,
            actualCount.get());
    verifyConnectionRequestedAndClosed(actualCount.get(), connectionManager);
}

From source file:com.flipkart.bifrost.ListenTest.java

@Test
public void testSendReceive() throws Exception {
    ObjectMapper mapper = new ObjectMapper();
    mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
    mapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY);

    Connection connection = new Connection(Lists.newArrayList("localhost"), "guest", "guest");
    connection.start();//from  www . ja  v a 2  s. com

    BifrostExecutor<Void> executor = BifrostExecutor.<Void>builder(TestAction.class).connection(connection)
            .objectMapper(mapper).requestQueue("bifrost-send").responseQueue("bifrost-recv").concurrency(20)
            .executorService(Executors.newFixedThreadPool(20)).build();

    BifrostRemoteCallExecutionServer<Void> executionServer = BifrostRemoteCallExecutionServer
            .<Void>builder(TestAction.class).objectMapper(mapper).connection(connection).concurrency(20)
            .requestQueue("bifrost-send").build();
    executionServer.start();

    long startTime = System.currentTimeMillis();
    AtomicInteger counter = new AtomicInteger(0);
    int requestCount = 1000000;
    CompletionService<Void> ecs = new ExecutorCompletionService<>(Executors.newFixedThreadPool(50));
    List<Future<Void>> futures = Lists.newArrayListWithCapacity(requestCount);
    for (int i = 0; i < requestCount; i++) {
        futures.add(ecs.submit(new ServiceCaller(executor, counter)));
    }
    for (int i = 0; i < requestCount; i++) {
        try {
            ecs.take().get();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
    }
    while (counter.get() != requestCount)
        ;
    System.out.println(
            String.format("Completed: %d in %d ms", counter.get(), (System.currentTimeMillis() - startTime)));
    executor.shutdown();
    executionServer.stop();
    connection.stop();

    Assert.assertEquals(requestCount, counter.get());
}

From source file:org.apache.hadoop.hbase.master.TestMasterOperationsForRegionReplicas.java

private void validateNumberOfRowsInMeta(final TableName table, int numRegions, Connection connection)
        throws IOException {
    assert (ADMIN.tableExists(table));
    final AtomicInteger count = new AtomicInteger();
    Visitor visitor = new Visitor() {
        @Override/*  w  ww  .j  a  v a  2  s . co  m*/
        public boolean visit(Result r) throws IOException {
            if (HRegionInfo.getHRegionInfo(r).getTable().equals(table))
                count.incrementAndGet();
            return true;
        }
    };
    MetaTableAccessor.fullScanRegions(connection, visitor);
    assert (count.get() == numRegions);
}

From source file:ufo.remote.calls.benchmark.client.caller.vertx.VertxClusterTester.java

@Override
protected void startTest(final TesterResult result) {

    EventBus bus = vertx.eventBus();// www. j  a  v a2  s.  c o m
    CountDownLatch latch = new CountDownLatch(result.totalCalls);
    AtomicInteger failures = new AtomicInteger(0);

    for (int i = 0; i < result.totalCalls; i++) {
        bus.send("echo", result.message, (AsyncResult<Message<String>> response) -> {

            if (response.failed()) {
                failures.incrementAndGet();
            }

            if (logger.isDebugEnabled()) {
                logger.debug("Received [{}]", response.result().body());
            }
            latch.countDown();
        });

    }

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

}

From source file:org.zodiark.service.action.ActionServiceImpl.java

/**
 * {@inheritDoc}//from  ww w  . j a v  a  2s . co m
 */
public void actionStarted(Envelope e) {
    try {
        final PublisherResults results = mapper.readValue(e.getMessage().getData(), PublisherResults.class);
        eventBus.message(RETRIEVE_PUBLISHER, results.getUuid(), new Reply<PublisherEndpoint, String>() {
            @Override
            public void ok(final PublisherEndpoint p) {

                final AtomicInteger time = new AtomicInteger(p.action().time());
                final AtmosphereResource publisher = p.resource();
                final AtmosphereResource subscriber = p.action().subscriber().resource();

                final Future<?> timerFuture = timer.scheduleAtFixedRate(new Runnable() {
                    @Override
                    public void run() {
                        if (time.get() == 0)
                            return;

                        Message m = new Message();
                        m.setPath(ACTION_TIMER);
                        try {
                            m.setData(mapper.writeValueAsString(time.getAndDecrement()));

                            Envelope e = Envelope.newPublisherMessage(p.uuid(), m);
                            String w = mapper.writeValueAsString(e);
                            publisher.write(w);

                            e = Envelope.newSubscriberMessage(p.uuid(), m);
                            w = mapper.writeValueAsString(e);
                            subscriber.write(w);
                        } catch (JsonProcessingException e1) {
                            logger.error("", e1);
                        }
                    }
                }, 1, 1, TimeUnit.SECONDS);

                timer.schedule(new Runnable() {
                    @Override
                    public void run() {
                        timerFuture.cancel(false);

                        Message m = new Message();
                        m.setPath(ACTION_COMPLETED);
                        try {
                            m.setData(mapper.writeValueAsString(new PublisherResults("OK")));

                            Envelope e = Envelope.newPublisherMessage(p.uuid(), m);
                            String w = mapper.writeValueAsString(e);
                            publisher.write(w);

                            m.setData(mapper.writeValueAsString(new SubscriberResults("OK")));
                            e = Envelope.newSubscriberMessage(p.uuid(), m);
                            w = mapper.writeValueAsString(e);
                            subscriber.write(w);
                        } catch (JsonProcessingException e1) {
                            logger.error("", e1);
                        } finally {
                            eventBus.message(STREAMING_COMPLETE_ACTION, p);
                        }
                    }
                }, p.action().time(), TimeUnit.SECONDS);
            }

            @Override
            public void fail(ReplyException replyException) {
                logger.error("Unable to retrieve Publishere for {}", results.getUuid());
            }
        });

    } catch (IOException e1) {
        logger.error("", e1);
    }

}

From source file:de.tudarmstadt.lt.seg.sentence.SentenceSplitterTest.java

@Test
public void ruleSplitterTest() {
    final AtomicInteger n = new AtomicInteger(0);
    ISentenceSplitter s = new RuleSplitter().initParam("default", false).init(TEST_TEXT);
    System.out.format("+++ %s +++ %n", s.getClass().getName());
    s.forEach(seg -> {//from  w  w w. j a v a2s  . co m
        if (seg.type == SegmentType.SENTENCE)
            n.incrementAndGet();
        System.out.println(seg);
    });
    System.out.println("+++");
    s.init(TokenizerTest.TEST_TEXT);
    s.forEach(seg -> {
        if (seg.type == SegmentType.SENTENCE)
            n.incrementAndGet();
        System.out.println(seg);
    });
    System.out.format("%d sentences.%n", n.get());
}

From source file:com.cloudera.lib.service.instrumentation.TestInstrumentationService.java

@Test
@TestDir/*from  w  w  w  . j  a v  a  2s  .  c o  m*/
@SuppressWarnings("unchecked")
public void sampling() throws Exception {
    String dir = getTestDir().getAbsolutePath();
    String services = StringUtils.toString(
            Arrays.asList(InstrumentationService.class.getName(), SchedulerService.class.getName()), ",");
    XConfiguration conf = new XConfiguration();
    conf.set("server.services", services);
    Server server = new Server("server", dir, dir, dir, dir, conf);
    server.init();
    Instrumentation instrumentation = server.get(Instrumentation.class);

    final AtomicInteger count = new AtomicInteger();

    Instrumentation.Variable<Long> varToSample = new Instrumentation.Variable<Long>() {
        @Override
        public Long getValue() {
            return (long) count.incrementAndGet();
        }
    };
    instrumentation.addSampler("g", "s", 10, varToSample);

    sleep(2000);
    int i = count.get();
    Assert.assertTrue(i > 0);

    Map<String, Map<String, ?>> snapshot = instrumentation.getSnapshot();
    Map<String, Map<String, Object>> samplers = (Map<String, Map<String, Object>>) snapshot.get("samplers");
    InstrumentationService.Sampler sampler = (InstrumentationService.Sampler) samplers.get("g").get("s");
    Assert.assertTrue(sampler.getRate() > 0);

    server.destroy();
}

From source file:org.apache.distributedlog.BKLogHandler.java

private void completeReadLogSegmentsFromStore(final Set<String> removedSegments,
        final Map<String, LogSegmentMetadata> addedSegments, final Comparator<LogSegmentMetadata> comparator,
        final CompletableFuture<Versioned<List<LogSegmentMetadata>>> readResult,
        final Version logSegmentNamesVersion, final AtomicInteger numChildren,
        final AtomicInteger numFailures) {
    if (0 != numChildren.decrementAndGet()) {
        return;/*  ww w  .j  a  v a  2  s .  c  o  m*/
    }
    if (numFailures.get() > 0) {
        return;
    }
    // update the cache only when fetch completed and before #getCachedLogSegments
    updateLogSegmentCache(removedSegments, addedSegments);
    List<LogSegmentMetadata> segmentList;
    try {
        segmentList = getCachedLogSegments(comparator);
    } catch (UnexpectedException e) {
        readResult.completeExceptionally(e);
        return;
    }
    readResult.complete(new Versioned<List<LogSegmentMetadata>>(segmentList, logSegmentNamesVersion));
}

From source file:com.vmware.admiral.adapter.docker.service.DockerNetworkAdapterService.java

private void processCreateNetwork(RequestContext context, int retriesCount) {
    AssertUtil.assertNotNull(context.networkState, "networkState");
    AssertUtil.assertNotEmpty(context.networkState.name, "networkState.name");

    CommandInput createCommandInput = context.commandInput
            .withPropertyIfNotNull(DOCKER_CONTAINER_NETWORK_NAME_PROP_NAME, context.networkState.name);
    if (context.networkState.driver != null && !context.networkState.driver.isEmpty()) {
        createCommandInput.withProperty(DOCKER_CONTAINER_NETWORK_DRIVER_PROP_NAME, context.networkState.driver);
    } else {//  w w w  . ja v  a2 s .com
        createCommandInput.withProperty(DOCKER_CONTAINER_NETWORK_DRIVER_PROP_NAME, DOCKER_NETWORK_TYPE_DEFAULT);
    }

    if (context.networkState.options != null && !context.networkState.options.isEmpty()) {
        createCommandInput.withProperty(DOCKER_CONTAINER_NETWORK_OPTIONS_PROP_NAME,
                context.networkState.options);
    }

    if (context.networkState.ipam != null) {
        createCommandInput.withProperty(DOCKER_CONTAINER_NETWORK_IPAM_PROP_NAME,
                DockerAdapterUtils.ipamToMap(context.networkState.ipam));
    }

    context.executor.createNetwork(createCommandInput, (op, ex) -> {
        if (ex != null) {
            AtomicInteger retryCount = new AtomicInteger(retriesCount);
            if (RETRIABLE_HTTP_STATUSES.contains(op.getStatusCode())
                    && retryCount.getAndIncrement() < NETWORK_CREATE_RETRIES_COUNT) {
                // retry if failure is retriable
                logWarning("Create network %s failed with %s. Retries left %d", context.networkState.name,
                        Utils.toString(ex), NETWORK_CREATE_RETRIES_COUNT - retryCount.get());
                processCreateNetwork(context, retryCount.get());
            } else {
                fail(context.request, op, ex);
            }
        } else {
            @SuppressWarnings("unchecked")
            Map<String, Object> body = op.getBody(Map.class);

            context.networkState.id = (String) body.get(DOCKER_CONTAINER_NETWORK_ID_PROP_NAME);
            inspectAndUpdateNetwork(context);
            // transition to TaskStage.FINISHED is done later, after the network state gets
            // updated
        }
    });
}