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.vladmihalcea.mongo.dao.ProductRepositoryIT.java

@Test
public void testRetries() throws InterruptedException {
    Product product = new Product();
    product.setId(123L);/*  w w w.  j a  v  a 2  s  . c o  m*/
    product.setName("Tv");
    productRepository.save(product);
    Product savedProduct = productRepository.findOne(123L);
    assertEquals(savedProduct, product);

    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
            public void run() {
                try {
                    startLatch.countDown();
                    startLatch.await();
                    productService.updateName(123L, 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:com.linkedin.pinot.core.data.manager.offline.OfflineTableDataManager.java

public void decrementCount(final String segmentId) {
    if (!_referenceCounts.containsKey(segmentId)) {
        LOGGER.warn("Received command to delete unexisting segment - " + segmentId);
        return;/* ww  w.  j av a2s . co  m*/
    }

    AtomicInteger count = _referenceCounts.get(segmentId);

    if (count.get() == 1) {
        OfflineSegmentDataManager segment = null;
        synchronized (getGlobalLock()) {
            if (count.get() == 1) {
                segment = _segmentsMap.remove(segmentId);
                _activeSegments.remove(segmentId);
                _referenceCounts.remove(segmentId);
            }
        }
        if (segment != null) {
            _currentNumberOfSegments.dec();
            _currentNumberOfDocuments.dec(segment.getSegment().getTotalDocs());
            _numDeletedSegments.inc();
            segment.getSegment().destroy();
        }
        LOGGER.info("Segment " + segmentId + " has been deleted");
        _segmentAsyncExecutorService.execute(new Runnable() {
            @Override
            public void run() {
                FileUtils.deleteQuietly(new File(_tableDataDir, segmentId));
                LOGGER.info("The index directory for the segment " + segmentId + " has been deleted");
            }
        });

    } else {
        count.decrementAndGet();
    }
}

From source file:com.graphaware.importer.stats.LoggingStatisticsCollector.java

/**
 * Print (log) all the stats for a given category.
 *
 * @param category to print./*from www .  j  av  a  2s .co m*/
 */
protected void printCategory(String category) {
    Map<String, AtomicInteger> stats = counters.get(category);
    for (String statistic : stats.keySet()) {
        StringBuilder spaces = new StringBuilder();
        AtomicInteger value = stats.get(statistic);
        int length = statistic.length() + value.toString().length();
        while (length + spaces.length() < DIVIDER.length() - 1) {
            spaces.append(" ");
        }
        LOG.info(statistic + ":" + spaces + value.get());
    }
}

From source file:org.apache.accumulo.server.util.RemoveEntriesForMissingFiles.java

private static int checkTable(ClientContext context, String table, Range range, boolean fix) throws Exception {

    @SuppressWarnings({ "rawtypes" })
    Map cache = new LRUMap(100000);
    Set<Path> processing = new HashSet<Path>();
    ExecutorService threadPool = Executors.newFixedThreadPool(16);

    System.out.printf("Scanning : %s %s\n", table, range);

    VolumeManager fs = VolumeManagerImpl.get();
    Connector connector = context.getConnector();
    Scanner metadata = connector.createScanner(table, Authorizations.EMPTY);
    metadata.setRange(range);//  w w  w  .  j  a  v  a2  s .com
    metadata.fetchColumnFamily(DataFileColumnFamily.NAME);
    int count = 0;
    AtomicInteger missing = new AtomicInteger(0);
    AtomicReference<Exception> exceptionRef = new AtomicReference<Exception>(null);
    BatchWriter writer = null;

    if (fix)
        writer = connector.createBatchWriter(MetadataTable.NAME, new BatchWriterConfig());

    for (Entry<Key, Value> entry : metadata) {
        if (exceptionRef.get() != null)
            break;

        count++;
        Key key = entry.getKey();
        Path map = fs.getFullPath(key);

        synchronized (processing) {
            while (processing.size() >= 64 || processing.contains(map))
                processing.wait();

            if (cache.get(map) != null) {
                continue;
            }

            processing.add(map);
        }

        threadPool.submit(new CheckFileTask(cache, fs, missing, writer, key, map, processing, exceptionRef));
    }

    threadPool.shutdown();

    synchronized (processing) {
        while (processing.size() > 0)
            processing.wait();
    }

    if (exceptionRef.get() != null)
        throw new AccumuloException(exceptionRef.get());

    if (writer != null && missing.get() > 0)
        writer.close();

    System.out.printf("Scan finished, %d files of %d missing\n\n", missing.get(), count);

    return missing.get();
}

From source file:com.stratio.decision.unit.engine.validator.BaseRegularExpressionValidatorTest.java

@Ignore
@Test//from   www. j a va2s .  com
public void mixedMessagesTest() {
    AtomicInteger count = new AtomicInteger(0);
    for (StratioStreamingMessage message : getMixedMessages()) {
        try {
            this.test(message);
        } catch (RequestValidationException e) {
            count.incrementAndGet();
        }
    }
    Assert.assertTrue(getBadStrings().length <= count.get());
}

From source file:io.microprofile.showcase.speaker.persistence.SpeakerDAO.java

@PostConstruct
private void initStore() {
    Logger.getLogger(SpeakerDAO.class.getName()).log(Level.INFO, "Initialise speaker DAO from bootstrap data");

    final Set<Speaker> featured = new HashSet<>(0);

    for (final Venue venue : this.venues) {
        featured.addAll(venue.getSpeakers());
    }/*w  w w  .ja  va2s . c om*/

    final AtomicInteger idc = new AtomicInteger(0);

    this.bootstrapData.getSpeaker().forEach(bootstrap -> {

        final int intId = Integer.valueOf(bootstrap.getId());

        if (intId > idc.get()) {
            idc.set(intId);
        }

        final String id = String.valueOf(intId);
        final String[] names = bootstrap.getFullName().split(" ");
        final Speaker sp = new Speaker();
        sp.setId(id);
        sp.setNameFirst(names[0].trim());
        sp.setNameLast(names[1].trim());
        sp.setOrganization(bootstrap.getCompany());
        sp.setBiography(bootstrap.getJobTitle());

        sp.setPicture("assets/images/unknown.jpg");

        appendFeatured(featured, sp);

        this.speakers.put(id, sp);
    });

    for (final Speaker fs : featured) {

        boolean found = false;

        for (final Speaker sp : this.speakers.values()) {
            if (fs.getNameFirst().toLowerCase().equals(sp.getNameFirst().toLowerCase())
                    && fs.getNameLast().toLowerCase().equals(sp.getNameLast().toLowerCase())) {
                found = true;
                break;
            }
        }

        if (!found) {
            fs.setId(String.valueOf(idc.incrementAndGet()));
            this.speakers.put(fs.getId(), fs);
        }
    }

    //TODO - Merge back to source json
}

From source file:hd3gtv.embddb.network.DataBlock.java

public String toString() {
    AtomicInteger all_size = new AtomicInteger(0);
    entries.forEach(block -> {//from  w w w  .  jav  a  2 s  .co  m
        all_size.addAndGet(block.getLen());
    });

    if (entries.size() == 1) {
        return request_name + " (" + all_size.get() + " bytes in 1 item)";
    } else {
        return request_name + " (" + all_size.get() + " bytes in " + entries.size() + " items)";
    }
}

From source file:ufo.remote.calls.benchmark.client.caller.resttemplate.AsyncRestTemplateTester.java

@Override
protected void startTest(final TesterResult result) {

    String url = "http://" + hostname + ":" + port + path;

    CountDownLatch latch = new CountDownLatch(result.totalCalls);
    AtomicInteger failures = new AtomicInteger(0);
    Executor executor = Executors.newFixedThreadPool(10);
    for (int i = 0; i < result.totalCalls; i++) {
        executor.execute(new Caller(url, result.message, latch, failures));
    }//from   w w  w  .j a v a 2s.  c  o  m

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

From source file:org.jboss.aerogear.test.api.extension.SenderStatisticsRequest.java

public void await(final int expectedTokenCount, Duration timeout) {

    final AtomicInteger found = new AtomicInteger();

    try {/* ww  w  .  ja  va  2 s .co  m*/
        Awaitility.await().atMost(timeout).until(new Callable<Boolean>() {
            @Override
            public Boolean call() throws Exception {
                SenderStatistics statistics = get();
                found.set(statistics.deviceTokens != null ? statistics.deviceTokens.size() : 0);
                return found.get() == expectedTokenCount;
            }
        });
    } catch (ConditionTimeoutException e) {
        System.err.println("SenderStats: Was expecting " + expectedTokenCount + " tokens but " + found.get()
                + " " + "were found.");
    }
}

From source file:com.ning.arecibo.util.timeline.samples.TestSampleCoder.java

@Test(groups = "fast")
public void testTimeRangeSampleProcessor() throws Exception {
    final DateTime startTime = new DateTime(dateFormatter.parseDateTime("2012-03-23T17:35:11.000Z"));
    final DateTime endTime = new DateTime(dateFormatter.parseDateTime("2012-03-23T17:35:17.000Z"));
    final int sampleCount = 2;

    final List<DateTime> dateTimes = ImmutableList.<DateTime>of(startTime, endTime);
    final byte[] compressedTimes = timelineCoder.compressDateTimes(dateTimes);
    final TimelineCursorImpl cursor = new TimelineCursorImpl(compressedTimes, sampleCount);
    Assert.assertEquals(cursor.getNextTime(), startTime);
    Assert.assertEquals(cursor.getNextTime(), endTime);

    // 2 x the value 12: REPEAT_BYTE, SHORT, 2, SHORT, 12 (2 bytes)
    final byte[] samples = new byte[] { (byte) 0xff, 2, 2, 0, 12 };

    final AtomicInteger samplesCount = new AtomicInteger(0);
    sampleCoder.scan(samples, compressedTimes, sampleCount, new TimeRangeSampleProcessor(startTime, endTime) {
        @Override//from ww  w.  j a  v a  2  s .com
        public void processOneSample(final DateTime time, final SampleOpcode opcode, final Object value) {
            if (samplesCount.get() == 0) {
                Assert.assertEquals(DateTimeUtils.unixSeconds(time), DateTimeUtils.unixSeconds(startTime));
            } else {
                Assert.assertEquals(DateTimeUtils.unixSeconds(time), DateTimeUtils.unixSeconds(endTime));
            }
            samplesCount.incrementAndGet();
        }
    });
    Assert.assertEquals(samplesCount.get(), sampleCount);
}