Example usage for java.util.concurrent.atomic AtomicLong addAndGet

List of usage examples for java.util.concurrent.atomic AtomicLong addAndGet

Introduction

In this page you can find the example usage for java.util.concurrent.atomic AtomicLong addAndGet.

Prototype

public final long addAndGet(long delta) 

Source Link

Document

Atomically adds the given value to the current value, with memory effects as specified by VarHandle#getAndAdd .

Usage

From source file:Main.java

public static void main(String[] argv) {
    AtomicLong nextId = new AtomicLong();

    System.out.println(nextId.getAndIncrement());
    System.out.println(nextId.addAndGet(100L));
}

From source file:org.languagetool.rules.spelling.morfologik.suggestions_ordering.SuggestionsOrdererTest.java

public static void main(String[] args) throws IOException {
    Map<String, JLanguageTool> ltMap = new HashMap<>();
    Map<String, Rule> rules = new HashMap<>();
    Map<String, SuggestionsOrderer> ordererMap = new HashMap<>();
    final AtomicInteger numOriginalCorrect = new AtomicInteger(0), numReorderedCorrect = new AtomicInteger(0),
            numOtherCorrect = new AtomicInteger(0), numBothCorrect = new AtomicInteger(0),
            numTotalReorderings = new AtomicInteger(0), numMatches = new AtomicInteger(0);
    AtomicLong totalReorderingComputationTime = new AtomicLong(0),
            totalHunspellComputationTime = new AtomicLong(0);
    Runtime.getRuntime()// w  ww . j  a  v  a 2  s .  c  om
            .addShutdownHook(new Thread(() -> System.out.printf(
                    "%n**** Correct Suggestions ****%nBoth: %d / Original: %d / Reordered: %d / Other: %d%n"
                            + "Average time per reordering: %fms / Average time in match(): %fms%n",
                    numBothCorrect.intValue(), numOriginalCorrect.intValue(), numReorderedCorrect.intValue(),
                    numOtherCorrect.intValue(),
                    (double) totalReorderingComputationTime.get() / numTotalReorderings.get(),
                    (double) totalHunspellComputationTime.get() / numMatches.get())));
    SuggestionsOrdererConfig.setNgramsPath(args[1]);
    try (CSVParser parser = new CSVParser(new FileReader(args[0]),
            CSVFormat.DEFAULT.withFirstRecordAsHeader())) {
        for (CSVRecord record : parser) {
            String lang = record.get("language");
            String covered = record.get("covered");
            String replacement = record.get("replacement");
            String sentenceStr = record.get("sentence");

            if (lang.equals("auto") || !(lang.equals("en-US") || lang.equals("de-DE"))) { // TODO: debugging only
                continue; // TODO do language detection?
            }
            Language language = Languages.getLanguageForShortCode(lang);
            JLanguageTool lt = ltMap.computeIfAbsent(lang, langCode -> new JLanguageTool(language));
            Rule spellerRule = rules.computeIfAbsent(lang, langCode -> lt.getAllRules().stream()
                    .filter(Rule::isDictionaryBasedSpellingRule).findFirst().orElse(null));
            if (spellerRule == null) {
                continue;
            }
            SuggestionsOrderer orderer = null;
            try {
                orderer = ordererMap.computeIfAbsent(lang,
                        langCode -> new SuggestionsOrdererGSoC(language, null, spellerRule.getId()));
            } catch (RuntimeException ignored) {
            }
            if (orderer == null) {
                continue;
            }
            numMatches.incrementAndGet();
            AnalyzedSentence sentence = lt.getAnalyzedSentence(sentenceStr);
            long startTime = System.currentTimeMillis();
            RuleMatch[] matches = spellerRule.match(sentence);
            totalHunspellComputationTime.addAndGet(System.currentTimeMillis() - startTime);
            for (RuleMatch match : matches) {
                String matchedWord = sentence.getText().substring(match.getFromPos(), match.getToPos());
                if (!matchedWord.equals(covered)) {
                    //System.out.println("Other spelling error detected, ignoring: " + matchedWord + " / " + covered);
                    continue;
                }
                List<String> original = match.getSuggestedReplacements();
                SuggestionsOrdererConfig.setMLSuggestionsOrderingEnabled(true);
                numTotalReorderings.incrementAndGet();
                startTime = System.currentTimeMillis();
                List<String> reordered = orderer.orderSuggestionsUsingModel(original, matchedWord, sentence,
                        match.getFromPos());
                totalReorderingComputationTime.addAndGet(System.currentTimeMillis() - startTime);
                SuggestionsOrdererConfig.setMLSuggestionsOrderingEnabled(false);
                if (original.isEmpty() || reordered.isEmpty()) {
                    continue;
                }
                String firstOriginal = original.get(0);
                String firstReordered = reordered.get(0);
                if (firstOriginal.equals(firstReordered)) {
                    if (firstOriginal.equals(replacement)) {
                        numBothCorrect.incrementAndGet();
                    } else {
                        numOtherCorrect.incrementAndGet();
                    }
                    //System.out.println("No change for match: " + matchedWord);
                } else {
                    System.out.println("Ordering changed for match " + matchedWord + ", before: "
                            + firstOriginal + ", after: " + firstReordered + ", choosen: " + replacement);
                    if (firstOriginal.equals(replacement)) {
                        numOriginalCorrect.incrementAndGet();
                    } else if (firstReordered.equals(replacement)) {
                        numReorderedCorrect.incrementAndGet();
                    } else {
                        numOtherCorrect.incrementAndGet();
                    }
                }
            }
        }
    }
}

From source file:com.taobao.tddl.interact.monitor.TotalStatMonitor.java

/**
 * normal db tab access counter//from  www . j a va  2s . com
 * 
 * @param key
 */
public static void dbTabIncrement(String key) {
    AtomicLong incre = dbTabMap.putIfAbsent(key, new AtomicLong(0));
    if (incre != null) {
        incre.addAndGet(1);
    }
}

From source file:com.taobao.tddl.interact.monitor.TotalStatMonitor.java

/**
 * virtual slot access counter/*from w  w w .ja  va2 s. co  m*/
 * 
 * @param key
 */
public static void virtualSlotIncrement(String key) {
    AtomicLong incre = virtualSlotMap.putIfAbsent(key, new AtomicLong(0));
    if (incre != null) {
        incre.addAndGet(1);
    }
}

From source file:io.druid.data.input.impl.prefetch.Fetcher.java

private static Closeable getFileCloser(final File file, final AtomicLong fetchedBytes) {
    return () -> {
        final long fileSize = file.length();
        file.delete();/*  w  w w.  ja  v a  2 s. c o  m*/
        fetchedBytes.addAndGet(-fileSize);
    };
}

From source file:org.apache.eagle.alert.engine.e2e.SampleClient2.java

private static Pair<Long, String> createFailureEntity(AtomicLong base, int hostIndex) {
    // TODO: add randomization
    IfEntity ie = new IfEntity();
    ie.host = "boot-vm-0-" + hostIndex + ".datacenter.corp.com";
    ie.instanceUuid = nextUuid;/* w ww.java 2  s. c om*/
    ie.message = "boot failure for when try start the given vm!";
    ie.reqId = nextReqId;
    ie.timestamp = base.get();

    base.addAndGet(2000);// simply some interval.
    return Pair.of(base.get(), JsonUtils.writeValueAsString(ie));
}

From source file:alluxio.cli.MiniBenchmark.java

/**
 * Reads a file.//  w  w  w. ja  v  a2s  .  co  m
 *
 * @param count the count to determine the filename
 * @throws Exception if it fails to read
 */
private static void readFile(CyclicBarrier barrier, AtomicLong runTime, int count) throws Exception {
    FileSystem fileSystem = FileSystem.Factory.get();
    byte[] buffer = new byte[(int) Math.min(sFileSize, 4 * Constants.MB)];

    barrier.await();
    long startTime = System.nanoTime();
    try (FileInStream inStream = fileSystem.openFile(filename(count))) {
        while (inStream.read(buffer) != -1) {
        }
    }
    runTime.addAndGet(System.nanoTime() - startTime);
}

From source file:org.roda.core.common.RodaUtils.java

/**
 * @deprecated 20160907 hsilva: not seeing any method using it, so it will be
 *             removed soon//from   w w  w.  j  av  a2s  .com
 */
@Deprecated
public static long getPathSize(Path startPath) throws IOException {
    final AtomicLong size = new AtomicLong(0);

    Files.walkFileTree(startPath, new SimpleFileVisitor<Path>() {
        @Override
        public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
            size.addAndGet(attrs.size());
            return FileVisitResult.CONTINUE;
        }

        @Override
        public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException {
            // Skip folders that can't be traversed
            return FileVisitResult.CONTINUE;
        }
    });

    return size.get();
}

From source file:org.apache.eagle.alert.engine.e2e.SampleClient2.java

private static Pair<Long, String> createLogEntity(AtomicLong base1, int hostIndex) {
    // TODO: add randomization
    LogEntity le = new LogEntity();
    if (hostIndex < 3) {
        le.component = "NOVA";
        le.host = "nova.000-" + hostIndex + ".datacenter.corp.com";
        le.message = "RabbitMQ Exception - MQ not connectable!";
    } else {/* w  ww . j  a v a 2s  .  c o m*/
        le.component = "NEUTRON";
        le.host = "neturon.000-" + (hostIndex - 3) + ".datacenter.corp.com";
        le.message = "DNS Exception - Fail to connect to DNS!";
    }
    le.instanceUuid = nextUuid;
    le.logLevel = "ERROR";
    le.reqId = nextReqId;
    le.timestamp = base1.get();

    base1.addAndGet(1000);// simply some interval.
    return Pair.of(base1.get(), JsonUtils.writeValueAsString(le));
}

From source file:alluxio.cli.MiniBenchmark.java

/**
 * Writes a file.//www.  j  a  v  a  2  s  . c o m
 *
 * @param count the count to determine the filename
 * @throws Exception if it fails to write
 */
private static void writeFile(CyclicBarrier barrier, AtomicLong runtime, int count) throws Exception {
    FileSystem fileSystem = FileSystem.Factory.get();
    byte[] buffer = new byte[(int) Math.min(sFileSize, 4 * Constants.MB)];
    Arrays.fill(buffer, (byte) 'a');
    AlluxioURI path = filename(count);

    if (fileSystem.exists(path)) {
        fileSystem.delete(path);
    }

    barrier.await();
    long startTime = System.nanoTime();
    long bytesWritten = 0;
    try (FileOutStream outStream = fileSystem.createFile(path)) {
        while (bytesWritten < sFileSize) {
            outStream.write(buffer, 0, (int) Math.min(buffer.length, sFileSize - bytesWritten));
            bytesWritten += buffer.length;
        }
    }
    runtime.addAndGet(System.nanoTime() - startTime);
}