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 NOT released if the user of the FcrepoClient does not handle the response
 * body at all./*from w  w w .j av  a2s  . c  om*/
 */
@Test
public void connectionNotReleasedWhenEntityBodyIgnored() {
    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, null);
        actualCount.getAndIncrement();
    });

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

From source file:com.spectralogic.ds3client.metadata.MetadataAccessImpl_Test.java

@Test
public void testMetadataAccessFailureHandlerWindows() {
    Assume.assumeTrue(Platform.isWindows());

    try {/*  w  w w .  ja va2  s  . c o m*/
        final ImmutableMap.Builder<String, Path> fileMapper = ImmutableMap.builder();

        final String fileName = "file";

        fileMapper.put(fileName, Paths.get(fileName));

        final AtomicInteger numTimesFailureHandlerCalled = new AtomicInteger(0);

        new MetadataAccessImpl(fileMapper.build(), new FailureEventListener() {
            @Override
            public void onFailure(final FailureEvent failureEvent) {
                numTimesFailureHandlerCalled.incrementAndGet();
                assertEquals(FailureEvent.FailureActivity.RecordingMetadata, failureEvent.doingWhat());
            }
        }, "localhost").getMetadataValue(fileName);

        assertEquals(1, numTimesFailureHandlerCalled.get());
    } catch (final Throwable t) {
        fail("Throwing exceptions from metadata est verbotten.");
    }
}

From source file:com.joyent.manta.client.jobs.MantaClientJobIT.java

@Test
public void canListOutputsForJobAsStrings() throws IOException, InterruptedException {
    String path1 = String.format("%s/%s", testPathPrefix, UUID.randomUUID());
    mantaClient.put(path1, TEST_DATA);/*www .  j  a  v a  2  s . com*/

    String path2 = String.format("%s/%s", testPathPrefix, UUID.randomUUID());
    mantaClient.put(path2, TEST_DATA);

    final MantaJob job = buildJob();
    final UUID jobId = mantaClient.createJob(job);

    List<String> inputs = new ArrayList<>();
    inputs.add(path1);
    inputs.add(path2);

    mantaClient.addJobInputs(jobId, inputs.iterator());
    Assert.assertTrue(mantaClient.endJobInput(jobId));

    awaitJobCompletion(jobId);

    final AtomicInteger count = new AtomicInteger(0);

    mantaClient.getJobOutputsAsStrings(jobId).forEach(content -> {
        count.incrementAndGet();
        Assert.assertEquals(content, TEST_DATA);
    });

    Assert.assertEquals(count.get(), 2, "Missing both outputs");
}

From source file:org.apache.hadoop.hbase.index.client.IndexAdmin.java

@Override
public void createTable(final HTableDescriptor desc, byte[][] splitKeys) throws IOException {
    try {/*from w  w w.ja  v a2  s.c om*/
        createTableAsync(desc, splitKeys);
    } catch (SocketTimeoutException ste) {
        LOG.warn("Creating " + desc.getNameAsString() + " took too long", ste);
    }
    int numRegs = splitKeys == null ? 1 : splitKeys.length + 1;
    int prevRegCount = 0;

    MetaScannerVisitorBaseWithTableName userTableVisitor = null;
    MetaScannerVisitorBaseWithTableName indexTableVisitor = null;
    boolean indexedHTD = desc.getValue(Constants.INDEX_SPEC_KEY) != null;

    for (int tries = 0; tries < this.numRetries * this.retryLongerMultiplier; ++tries) {

        AtomicInteger actualRegCount = null;
        // Wait for new table to come on-line
        if (userTableVisitor == null) {
            userTableVisitor = new MetaScannerVisitorBaseWithTableName(desc.getNameAsString());
        }
        actualRegCount = userTableVisitor.getActualRgnCnt();
        actualRegCount.set(0);
        MetaScanner.metaScan(getConfiguration(), getConnection(), userTableVisitor, desc.getTableName());
        if (actualRegCount.get() != numRegs) {
            if (tries == this.numRetries * this.retryLongerMultiplier - 1) {
                throw new RegionOfflineException("Only " + actualRegCount.get() + " of " + numRegs
                        + " regions are online; retries exhausted.");
            }
            try { // Sleep
                Thread.sleep(getPauseTime(tries));
            } catch (InterruptedException e) {
                throw new InterruptedIOException("Interrupted when opening" + " regions; "
                        + actualRegCount.get() + " of " + numRegs + " regions processed so far");
            }
            if (actualRegCount.get() > prevRegCount) { // Making progress
                prevRegCount = actualRegCount.get();
                tries = -1;
            }
        } else {
            if (indexedHTD) {
                TableName indexTableName = TableName.valueOf(IndexUtils.getIndexTableName(desc.getName()));
                if (indexTableVisitor == null) {
                    indexTableVisitor = new MetaScannerVisitorBaseWithTableName(
                            indexTableName.getNameAsString());
                }
                actualRegCount = indexTableVisitor.getActualRgnCnt();
                actualRegCount.set(0);
                MetaScanner.metaScan(getConfiguration(), getConnection(), indexTableVisitor, indexTableName);
                if (actualRegCount.get() != numRegs) {
                    if (tries == this.numRetries * this.retryLongerMultiplier - 1) {
                        throw new RegionOfflineException("Only " + actualRegCount.get() + " of " + numRegs
                                + " regions are online; retries exhausted.");
                    }
                    try { // Sleep
                        Thread.sleep(getPauseTime(tries));
                    } catch (InterruptedException e) {
                        throw new InterruptedIOException("Interrupted when opening" + " regions; "
                                + actualRegCount.get() + " of " + numRegs + " regions processed so far");
                    }
                    if (actualRegCount.get() > prevRegCount) { // Making progress
                        prevRegCount = actualRegCount.get();
                        tries = -1;
                    }
                } else if (isTableEnabled(indexTableName)) {
                    return;
                }
            } else if (isTableEnabled(desc.getName())) {
                return;
            }
        }
    }
    throw new TableNotEnabledException(
            "Retries exhausted while still waiting for table: " + desc.getNameAsString() + " to be enabled");
}

From source file:com.rapplogic.aru.uploader.wifi.WifiSketchUploader.java

@Override
protected void open(final Map<String, Object> context) throws Exception {

    String host = (String) context.get("host");
    Integer port = (Integer) context.get("port");
    Integer connectionTimeoutSecs = (Integer) context.get("connectionTimeoutSecs");
    Integer readTimeoutSecs = (Integer) context.get("readTimeoutSecs");

    // open socket
    socket = new Socket();
    socket.connect(new InetSocketAddress(host, port), connectionTimeoutSecs * 1000);
    socket.setSoTimeout(readTimeoutSecs * 1000);

    connected = true;// ww w  .  jav a  2 s.co  m

    final int[] reply = new int[5];
    final AtomicInteger replyIndex = new AtomicInteger(0);

    // TODO unlike other wireless protocols, wifi is stateful so we need to handle situations where we lose the socket and reconnect

    t = new Thread(new Runnable() {
        @Override
        public void run() {
            int ch = 0;

            // reply always terminated with 13,10
            try {
                while ((ch = socket.getInputStream().read()) > -1) {
                    if (replyIndex.get() < reply.length) {
                        reply[replyIndex.getAndIncrement()] = ch;
                    } else if (replyIndex.get() == 5 && ch == 13) {
                        replyIndex.getAndIncrement();
                        // discard
                    } else if (replyIndex.get() == 6 && ch == 10) {
                        //System.out.println("reply is " + stringBuilder.toString());
                        //                  stringBuilder = new StringBuilder();
                        handleReply(reply);
                        replyIndex.set(0);
                    } else {
                        //error
                        throw new RuntimeException("Expected CR/LF -- invalid reply at position "
                                + replyIndex.get() + ", array: " + intArrayToString(reply));
                    }
                }
            } catch (IOException e) {
                if (!connected && e instanceof SocketException) {
                    // expected.. ignore
                } else {
                    System.out.println("IO error in socket reader");
                    e.printStackTrace();
                }
            } catch (Exception e) {
                System.out.println("Unexpected error in socket reader");
                e.printStackTrace();
            }

            connected = false;
        }
    });

    t.setDaemon(true);
    t.start();
}

From source file:org.jtheque.features.FeatureServiceTest.java

@Test
public void listenerNotCalledAfterRemoved() {
    final AtomicInteger addCounter = new AtomicInteger(0);
    final AtomicInteger removeCounter = new AtomicInteger(0);
    final AtomicInteger modifyCounter = new AtomicInteger(0);

    FeatureListener listener = new MyFeatureListener(addCounter, removeCounter, modifyCounter);

    featureService.addFeatureListener(listener);

    featureService.addMenu("no-module", new MenuMain());

    featureService.removeFeatureListener(listener);

    featureService.addMenu("no-module-2", new MenuMain());

    assertEquals(1, addCounter.get());
    assertEquals(0, removeCounter.get());
    assertEquals(0, modifyCounter.get());
}

From source file:com.twitter.distributedlog.auditor.DLAuditor.java

static <T> void executeAction(final LinkedBlockingQueue<T> queue, final int numThreads, final Action<T> action)
        throws IOException {
    final CountDownLatch failureLatch = new CountDownLatch(1);
    final CountDownLatch doneLatch = new CountDownLatch(queue.size());
    final AtomicInteger numFailures = new AtomicInteger(0);
    final AtomicInteger completedThreads = new AtomicInteger(0);

    ExecutorService executorService = Executors.newFixedThreadPool(numThreads);
    try {/*from ww  w .j ava 2 s .  com*/
        for (int i = 0; i < numThreads; i++) {
            executorService.submit(new Runnable() {
                @Override
                public void run() {
                    while (true) {
                        T item = queue.poll();
                        if (null == item) {
                            break;
                        }
                        try {
                            action.execute(item);
                        } catch (IOException ioe) {
                            logger.error("Failed to execute action on item '{}'", item, ioe);
                            numFailures.incrementAndGet();
                            failureLatch.countDown();
                            break;
                        }
                        doneLatch.countDown();
                    }
                    if (numFailures.get() == 0 && completedThreads.incrementAndGet() == numThreads) {
                        failureLatch.countDown();
                    }
                }
            });
        }
        try {
            failureLatch.await();
            if (numFailures.get() > 0) {
                throw new IOException("Encountered " + numFailures.get() + " failures on executing action.");
            }
            doneLatch.await();
        } catch (InterruptedException ie) {
            Thread.currentThread().interrupt();
            logger.warn("Interrupted on executing action", ie);
            throw new DLInterruptedException("Interrupted on executing action", ie);
        }
    } finally {
        executorService.shutdown();
    }
}

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

@SuppressWarnings("unchecked")
@Test//from w w w.ja  v a  2s .  c o m
public void subscribeToThreeRelatedPipelineOutputs() {

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

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

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

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

@SuppressWarnings("unchecked")
@Test/*from  w ww.  j  a  v a  2s .c  om*/
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:io.wcm.caravan.pipeline.impl.JsonPipelineMultipleSubscriptionsTest.java

@SuppressWarnings("unchecked")
@Test/*from   w  w  w.j av a  2s . co  m*/
public void test3StepPipelineActionCallsMixedOrder() {

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

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

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