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.netflix.spinnaker.front50.migrations.LinearToParallelMigration.java

private void migrate(ItemDAO<Pipeline> dao, String type, Pipeline pipeline) {
    log.info(format("Migrating %s '%s' from linear -> parallel", type, pipeline.getId()));

    AtomicInteger refId = new AtomicInteger(0);
    List<Map<String, Object>> stages = (List<Map<String, Object>>) pipeline.getOrDefault("stages",
            Collections.emptyList());
    stages.forEach(stage -> {// w ww.  j av a2s . c o m
        stage.put("refId", String.valueOf(refId.get()));
        if (refId.get() > 0) {
            stage.put("requisiteStageRefIds", Collections.singletonList(String.valueOf(refId.get() - 1)));
        } else {
            stage.put("requisiteStageRefIds", Collections.emptyList());
        }

        refId.incrementAndGet();
    });

    pipeline.put("parallel", true);
    dao.update(pipeline.getId(), pipeline);

    log.info(format("Migrated %s '%s' from linear -> parallel", type, pipeline.getId()));
}

From source file:com.ewcms.web.pubsub.ProgressSender.java

@Override
protected String constructOutput() {
    List<Taskable> tasks = publishFac.getSitePublishTasks(siteId);

    StringBuilder builder = new StringBuilder();

    builder.append(" <script type=\"text/javascript\">");
    builder.append("parent.loadData(");
    AtomicInteger count = new AtomicInteger(0);
    builder.append("{\"rows\":[");
    for (Taskable task : tasks) {
        constructTreeGridRows(builder, count, -1, task);
    }/*from ww w.j ava2s. co  m*/
    builder.append("]");
    builder.append(",\"total\":").append(count.get()).append("}");
    builder.append(");");
    builder.append("</script>");
    return builder.toString();
}

From source file:com.vladmihalcea.OptimisticLockingTest.java

@Test
public void testRetries() throws InterruptedException {
    final Product product = productService.newProduct();
    assertEquals(0, product.getVersion());
    Product savedProduct = productService.updateName(product.getId(), "name");
    assertEquals(1, savedProduct.getVersion());

    final int threadsNumber = 10;

    final AtomicInteger atomicInteger = new AtomicInteger();
    final CountDownLatch startLatch = new CountDownLatch(threadsNumber + 1);
    final CountDownLatch endLatch = new CountDownLatch(threadsNumber + 1);

    for (; atomicInteger.get() < threadsNumber; atomicInteger.incrementAndGet()) {
        final long index = (long) atomicInteger.get() * threadsNumber;
        LOGGER.info("Scheduling thread index {}", index);
        Thread testThread = new Thread(new Runnable() {
            @Override//ww  w.java 2s. c om
            public void run() {
                try {
                    startLatch.countDown();
                    startLatch.await();
                    productService.updateName(product.getId(), UUID.randomUUID().toString());
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                } catch (Exception e) {
                    LOGGER.error("Exception thrown!", e);
                } finally {
                    endLatch.countDown();
                }
            }
        });
        testThread.start();
    }
    startLatch.countDown();
    LOGGER.info("Waiting for threads to be done");
    endLatch.countDown();
    endLatch.await();
    LOGGER.info("Threads are done");
}

From source file:org.apache.hadoop.fs.FCStatisticsBaseTest.java

@Test(timeout = 70000)
public void testStatisticsThreadLocalDataCleanUp() throws Exception {
    final Statistics stats = new Statistics("test");
    // create a small thread pool to test the statistics
    final int size = 2;
    ExecutorService es = Executors.newFixedThreadPool(size);
    List<Callable<Boolean>> tasks = new ArrayList<Callable<Boolean>>(size);
    for (int i = 0; i < size; i++) {
        tasks.add(new Callable<Boolean>() {
            public Boolean call() {
                // this populates the data set in statistics
                stats.incrementReadOps(1);
                return true;
            }//from   w  ww.  jav  a 2 s .c o m
        });
    }
    // run the threads
    es.invokeAll(tasks);
    // assert that the data size is exactly the number of threads
    final AtomicInteger allDataSize = new AtomicInteger(0);
    allDataSize.set(stats.getAllThreadLocalDataSize());
    Assert.assertEquals(size, allDataSize.get());
    Assert.assertEquals(size, stats.getReadOps());
    // force the GC to collect the threads by shutting down the thread pool
    es.shutdownNow();
    es.awaitTermination(1, TimeUnit.MINUTES);
    es = null;
    System.gc(); // force GC to garbage collect threads

    // wait for up to 60 seconds
    GenericTestUtils.waitFor(new Supplier<Boolean>() {
        @Override
        public Boolean get() {
            int size = stats.getAllThreadLocalDataSize();
            allDataSize.set(size);
            if (size == 0) {
                return true;
            }
            LOG.warn(
                    "not all references have been cleaned up; still " + allDataSize.get() + " references left");
            LOG.warn("triggering another GC");
            System.gc();
            return false;
        }
    }, 500, 60 * 1000);
    Assert.assertEquals(0, allDataSize.get());
    Assert.assertEquals(size, stats.getReadOps());
}

From source file:cf.spring.servicebroker.ServiceBrokerTest.java

@Test
public void unbind() throws Exception {
    final AtomicInteger unbindCounter = context.getBean("unbindCounter", AtomicInteger.class);
    assertEquals(unbindCounter.get(), 0);

    final HttpUriRequest unbindRequest = RequestBuilder.delete()
            .setUri(bindingUri + "?service_id=" + BROKER_ID_STATIC + "&" + "plan_id=" + PLAN_ID).build();
    final CloseableHttpResponse unbindResponse = client.execute(unbindRequest);
    assertEquals(unbindResponse.getStatusLine().getStatusCode(), 200);
    assertEquals(unbindCounter.get(), 1);
}

From source file:cf.spring.servicebroker.ServiceBrokerTest.java

@Test
public void bind() throws Exception {
    final AtomicInteger bindCounter = context.getBean("bindCounter", AtomicInteger.class);
    assertEquals(bindCounter.get(), 0);
    // Do bind//w ww.  j ava2 s .co m
    final ServiceBrokerHandler.BindBody bindBody = new ServiceBrokerHandler.BindBody(BROKER_ID_STATIC, PLAN_ID,
            APPLICATION_GUID);
    final HttpUriRequest bindRequest = RequestBuilder.put().setUri(bindingUri)
            .setEntity(new StringEntity(mapper.writeValueAsString(bindBody), ContentType.APPLICATION_JSON))
            .build();
    final CloseableHttpResponse bindResponse = client.execute(bindRequest);
    assertEquals(bindResponse.getStatusLine().getStatusCode(), 201);
    assertEquals(bindCounter.get(), 1);
    final JsonNode bindResponseJson = mapper.readTree(bindResponse.getEntity().getContent());
    assertTrue(bindResponseJson.has("credentials"));
    assertFalse(bindResponseJson.has("syslog_drain_url"));

    final JsonNode credentials = bindResponseJson.get("credentials");
    assertEquals(credentials.get("username").asText(), SOME_USERNAME);
    assertEquals(credentials.get("password").asText(), SOME_PASSWORD);
}

From source file:cf.spring.servicebroker.ServiceBrokerTest.java

@Test
public void deprovision() throws Exception {
    final AtomicInteger deprovisionCounter = context.getBean("deprovisionCounter", AtomicInteger.class);
    assertEquals(deprovisionCounter.get(), 0);

    // Do deprovision
    final HttpUriRequest deprovisionRequest = RequestBuilder.delete()
            .setUri(instanceUri + "?service_id=" + BROKER_ID_STATIC + "&" + "plan_id=" + PLAN_ID).build();
    final CloseableHttpResponse deprovisionResponse = client.execute(deprovisionRequest);
    assertEquals(deprovisionResponse.getStatusLine().getStatusCode(), 200);
    assertEquals(deprovisionCounter.get(), 1);
}

From source file:org.alfresco.bm.event.AbstractResultService.java

/**
 * Reports the oldest stats for the events and pops it off the list
 * /* w  ww.j a  v a  2 s  .c  o  m*/
 * @param windowMultiple        the number of reporting entries to hold per event
 * @return                      <tt>true</tt> to stop processing
 */
private boolean reportAndCycleStats(Map<String, LinkedList<DescriptiveStatistics>> statsByEventName,
        Map<String, LinkedList<AtomicInteger>> failuresByEventName, long currentWindowStartTime,
        long currentWindowEndTime, int windowMultiple, ResultHandler handler) {
    // Handle stats
    Map<String, DescriptiveStatistics> stats = new HashMap<String, DescriptiveStatistics>(
            statsByEventName.size() + 7);
    for (Map.Entry<String, LinkedList<DescriptiveStatistics>> entry : statsByEventName.entrySet()) {
        // Grab the OLDEST stats from the beginning of the list
        String eventName = entry.getKey();
        LinkedList<DescriptiveStatistics> ll = entry.getValue();
        try {
            DescriptiveStatistics eventStats = ll.getFirst();
            stats.put(eventName, eventStats);
            if (ll.size() == windowMultiple) {
                // We have enough reporting points for the window, so pop the first and add a new to the end
                ll.pop();
            }
            ll.add(new DescriptiveStatistics());
        } catch (NoSuchElementException e) {
            throw new RuntimeException(
                    "An event name did not have a result for the reporting period: " + statsByEventName);
        }
    }

    // Handle failures
    Map<String, Integer> failures = new HashMap<String, Integer>(statsByEventName.size() + 7);
    for (Map.Entry<String, LinkedList<AtomicInteger>> entry : failuresByEventName.entrySet()) {
        // Grab the OLDEST stats from the beginning of the list
        String eventName = entry.getKey();
        LinkedList<AtomicInteger> ll = entry.getValue();
        try {
            AtomicInteger eventFailures = ll.getFirst();
            failures.put(eventName, Integer.valueOf(eventFailures.get()));
            if (ll.size() == windowMultiple) {
                // We have enough reporting points for the window, so pop the first and add a new to the end
                ll.pop();
            }
            ll.add(new AtomicInteger());
        } catch (NoSuchElementException e) {
            throw new RuntimeException("An event name did not have a failure count for the reporting period: "
                    + failuresByEventName);
        }
    }

    boolean stop = false;
    try {
        boolean go = handler.processResult(currentWindowStartTime, currentWindowEndTime, stats, failures);
        stop = !go;
    } catch (Throwable e) {
        logger.error("Exception while making callback.", e);
    }
    return stop;
}

From source file:com.indeed.lsmtree.core.TestStore.java

public void testStore(StorageType storageType, CompressionCodec codec) throws Exception {
    File indexDir = new File(tmpDir, "index");
    indexDir.mkdirs();// w w  w .  ja v  a  2s  .  c  o  m
    File indexLink = new File(tmpDir, "indexlink");
    PosixFileOperations.link(indexDir, indexLink);
    File storeDir = new File(indexLink, "store");
    Store<Integer, Long> store = new StoreBuilder<Integer, Long>(storeDir, new IntSerializer(),
            new LongSerializer()).setMaxVolatileGenerationSize(8 * 1024 * 1024).setStorageType(storageType)
                    .setCodec(codec).build();
    final Random r = new Random(0);
    final int[] ints = new int[treeSize];
    for (int i = 0; i < ints.length; i++) {
        ints[i] = r.nextInt();
    }
    for (final int i : ints) {
        store.put(i, (long) i);
        assertTrue(store.get(i) == i);
    }
    for (final int i : ints) {
        assertTrue(store.get(i) == i);
    }
    store.close();
    store.waitForCompactions();
    store = new StoreBuilder<Integer, Long>(storeDir, new IntSerializer(), new LongSerializer())
            .setMaxVolatileGenerationSize(8 * 1024 * 1024).setStorageType(storageType).setCodec(codec).build();
    Arrays.sort(ints);
    Iterator<Store.Entry<Integer, Long>> iterator = store.iterator();
    int index = 0;
    while (iterator.hasNext()) {
        Store.Entry<Integer, Long> next = iterator.next();
        int current = ints[index];
        assertTrue(next.getKey() == ints[index]);
        assertTrue(next.getValue() == ints[index]);
        while (index < ints.length && ints[index] == current) {
            index++;
        }
    }
    assertTrue(index == ints.length);
    final BitSet deleted = new BitSet();
    for (int i = 0; i < ints.length / 10; i++) {
        int deletionIndex = r.nextInt(ints.length);
        deleted.set(deletionIndex, true);
        for (int j = deletionIndex - 1; j >= 0; j--) {
            if (ints[j] == ints[deletionIndex]) {
                deleted.set(j, true);
            } else {
                break;
            }
        }
        for (int j = deletionIndex + 1; j < ints.length; j++) {
            if (ints[j] == ints[deletionIndex]) {
                deleted.set(j, true);
            } else {
                break;
            }
        }
        store.delete(ints[deletionIndex]);
        assertNull(store.get(ints[deletionIndex]));
    }
    iterator = store.iterator();
    index = 0;
    while (iterator.hasNext()) {
        Store.Entry<Integer, Long> next = iterator.next();
        while (deleted.get(index))
            index++;
        int current = ints[index];
        assertTrue(next.getKey() == ints[index]);
        assertTrue(next.getValue() == ints[index]);
        while (index < ints.length && ints[index] == current) {
            index++;
        }
    }
    while (deleted.get(index))
        index++;
    assertTrue(index == ints.length);
    final int max = ints[ints.length - 1];
    final AtomicInteger done = new AtomicInteger(8);
    for (int i = 0; i < done.get(); i++) {
        final int thread = i;
        final Store<Integer, Long> finalStore = store;
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Random r = new Random(thread);
                    for (int i = 0; i < treeSize; i++) {
                        int rand = r.nextInt();
                        int insertionindex = Arrays.binarySearch(ints, rand);

                        Store.Entry<Integer, Long> next = finalStore.ceil(rand);
                        boolean found = next != null;
                        if (insertionindex >= 0 && deleted.get(insertionindex)) {
                            assertNull(finalStore.get(ints[insertionindex]));
                        } else {
                            assertTrue(found == (rand <= max));
                            if (found) {
                                assertTrue(next.getKey() >= rand);
                                assertTrue(next.getKey().longValue() == next.getValue());
                                if (insertionindex >= 0) {
                                    assertTrue(rand == ints[insertionindex]);
                                    assertTrue(next.getKey() == rand);
                                    Long result = finalStore.get(rand);
                                    assertTrue(result == rand);
                                } else {
                                    int nextIndex = ~insertionindex;
                                    while (deleted.get(nextIndex) && nextIndex < ints.length)
                                        nextIndex++;
                                    if (nextIndex < ints.length) {
                                        if (insertionindex != -1)
                                            assertTrue(ints[(~insertionindex) - 1] < rand);
                                        assertTrue(ints[nextIndex] + " != " + next.getKey(),
                                                ints[nextIndex] == next.getKey());

                                    }
                                    Long result = finalStore.get(rand);
                                    assertTrue(result == null);
                                }
                            }
                        }
                    }
                } catch (IOException e) {
                    throw new RuntimeException(e);
                } finally {
                    done.decrementAndGet();
                }
            }
        }).start();
    }
    while (done.get() > 0) {
        Thread.yield();
    }
    store.close();
}

From source file:org.apache.camel.processor.LoopProcessor.java

protected boolean process(final Exchange exchange, final AsyncCallback callback, final AtomicInteger index,
        final AtomicInteger count) {

    // set current index as property
    if (LOG.isDebugEnabled()) {
        LOG.debug("LoopProcessor: iteration #" + index.get());
    }/*from w w  w.jav a  2 s  . c  o m*/
    exchange.setProperty(Exchange.LOOP_INDEX, index.get());

    boolean sync = processNext(exchange, new AsyncCallback() {
        public void done(boolean doneSync) {
            // we only have to handle async completion of the routing slip
            if (doneSync) {
                return;
            }

            // increment index as we have just processed once
            index.getAndIncrement();

            // continue looping asynchronously
            while (index.get() < count.get()) {

                // and prepare for next iteration
                ExchangeHelper.prepareOutToIn(exchange);

                // process again
                boolean sync = process(exchange, callback, index, count);
                if (!sync) {
                    if (LOG.isTraceEnabled()) {
                        LOG.trace("Processing exchangeId: " + exchange.getExchangeId()
                                + " is continued being processed asynchronously");
                    }
                    // the remainder of the routing slip will be completed async
                    // so we break out now, then the callback will be invoked which then continue routing from where we left here
                    return;
                }

                // increment counter before next loop
                index.getAndIncrement();
            }

            // we are done so prepare the result
            ExchangeHelper.prepareOutToIn(exchange);
            if (LOG.isTraceEnabled()) {
                LOG.trace(
                        "Processing complete for exchangeId: " + exchange.getExchangeId() + " >>> " + exchange);
            }
            callback.done(false);
        }
    });

    return sync;
}