Example usage for java.util.concurrent.atomic AtomicInteger set

List of usage examples for java.util.concurrent.atomic AtomicInteger set

Introduction

In this page you can find the example usage for java.util.concurrent.atomic AtomicInteger set.

Prototype

public final void set(int newValue) 

Source Link

Document

Sets the value to newValue , with memory effects as specified by VarHandle#setVolatile .

Usage

From source file:org.bpmscript.process.lock.LockingInstanceManager.java

/**
 * Locks on the processInstanceId// ww  w. ja  v  a2s. c om
 */
public IExecutorResult doWithInstance(final String processInstanceId, final IInstanceCallback callback)
        throws Exception {
    AtomicInteger lock = null;
    synchronized (locks) {
        lock = locks.get(processInstanceId);
        if (lock == null) {
            lock = new AtomicInteger(1);
            locks.put(processInstanceId, lock);
        } else {
            lock.set(lock.get() + 1);
        }
    }
    IExecutorResult result = null;
    synchronized (lock) {
        try {
            log.debug("locking " + processInstanceId + " " + lock);
            result = instanceManager.doWithInstance(processInstanceId, callback);
        } finally {
            log.debug("unlocking " + processInstanceId);
            lock.set(lock.get() - 1);
            if (lock.get() == 0) {
                locks.remove(processInstanceId);
            }
        }
    }
    return result;
}

From source file:org.neo4j.server.enterprise.ArbiterBootstrapperIT.java

private Adapter joinAwaitingListener(final CountDownLatch latch, final AtomicInteger port) {
    return new ClusterListener.Adapter() {
        @Override/*from w w  w.jav a  2 s  . co m*/
        public void joinedCluster(InstanceId member, URI memberUri) {
            port.set(memberUri.getPort());
            latch.countDown();
            clients[0].removeClusterListener(this);
        }
    };
}

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 {//  w w  w. jav  a  2 s. c  o 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.thoughtworks.go.buildsession.ExecCommandExecutor.java

private int executeCommandLine(final BuildSession buildSession, final CommandLine commandLine) {
    final AtomicInteger exitCode = new AtomicInteger(-1);
    final CountDownLatch canceledOrDone = new CountDownLatch(1);
    buildSession.submitRunnable(new Runnable() {
        @Override//  w w w .  j av  a2s .c o  m
        public void run() {
            try {
                exitCode.set(commandLine.run(buildSession.processOutputStreamConsumer(), null));
            } catch (CommandLineException e) {
                LOG.error("Command failed", e);
                String message = format(
                        "Error happened while attempting to execute '%s'. \nPlease make sure [%s] can be executed on this agent.\n",
                        commandLine.toStringForDisplay(), commandLine.getExecutable());
                String path = System.getenv("PATH");
                buildSession.println(message);
                buildSession.println(format("[Debug Information] Environment variable PATH: %s", path));
                LOG.error(format("[Command Line] %s. Path: %s", message, path));
            } finally {
                canceledOrDone.countDown();
            }
        }
    });

    Future<?> cancelMonitor = buildSession.submitRunnable(new Runnable() {
        @Override
        public void run() {
            try {
                buildSession.waitUntilCanceled();
            } catch (InterruptedException e) {
                // ignore
            } finally {
                canceledOrDone.countDown();
            }
        }
    });

    try {
        canceledOrDone.await();
    } catch (InterruptedException e) {
        LOG.error("Building thread interrupted", e);
    }
    cancelMonitor.cancel(true);
    return exitCode.get();
}

From source file:gov.pnnl.goss.gridappsd.process.ProcessManagerImpl.java

public int assignSimulationPort(int simulationId) throws Exception {
    Integer simIdKey = new Integer(simulationId);
    if (!simulationPorts.containsKey(simIdKey)) {
        int tempPort = 49152 + randPort.nextInt(16384);
        AtomicInteger tempPortObj = new AtomicInteger(tempPort);
        while (simulationPorts.containsValue(tempPortObj)) {
            int newTempPort = 49152 + randPort.nextInt(16384);
            tempPortObj.set(newTempPort);
        }/*from   w w  w.j a  v a 2  s.com*/
        simulationPorts.put(simIdKey, tempPortObj);
        return tempPortObj.get();
        //TODO: test host:port is available
    } else {
        throw new Exception(
                "The simulation id already exists. This indicates that the simulation id is part of a"
                        + "simulation in progress.");
    }
}

From source file:org.apache.solr.client.solrj.impl.HttpClientUtilTest.java

@Test
public void testReplaceConfigurer() throws IOException {

    try {/*from www .j  a  va2s . co  m*/
        final AtomicInteger counter = new AtomicInteger();
        HttpClientConfigurer custom = new HttpClientConfigurer() {
            @Override
            public void configure(DefaultHttpClient httpClient, SolrParams config) {
                super.configure(httpClient, config);
                counter.set(config.getInt("custom-param", -1));
            }

        };

        HttpClientUtil.setConfigurer(custom);

        ModifiableSolrParams params = new ModifiableSolrParams();
        params.set("custom-param", 5);
        HttpClientUtil.createClient(params).close();
        assertEquals(5, counter.get());
    } finally {
        //restore default configurer
        HttpClientUtil.setConfigurer(new HttpClientConfigurer());
    }

}

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());
    }//from ww w.j  a v a 2  s  .  com

    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:fr.landel.utils.assertor.utils.AssertorMap.java

private static <M extends Map<K, V>, K, V, T> boolean hasInOrder(final M map, final Iterable<T> objects,
        final boolean not, final EnumAnalysisMode analysisMode,
        final BiPredicate<Entry<K, V>, T> entriesEqualChecker, final Class<T> objectsClass) {

    int found = 0;

    final int size1 = map.size();
    final int size2 = IterableUtils.size(objects);

    if (size1 < size2) {
        return not;
    }/*from   ww  w .j  a v a  2  s  .  c o  m*/

    final Set<Entry<K, V>> entries1 = map.entrySet();
    final List<T> entries2 = IterableUtils.toList(objects);

    if (EnumAnalysisMode.STANDARD.equals(analysisMode)) {
        for (Entry<K, V> entry1 : entries1) {
            if (found < size2) {
                if (entriesEqualChecker.test(entry1, entries2.get(found))) {
                    ++found;
                } else if (found > 0) {
                    found = 0;
                }
            }
        }
    } else {
        final AtomicInteger count = new AtomicInteger(0);

        final Stream<Entry<K, V>> stream;
        if (EnumAnalysisMode.PARALLEL.equals(analysisMode)) {
            stream = entries1.parallelStream();
        } else {
            stream = entries1.stream();
        }

        stream.forEachOrdered(o -> {
            int inc = count.get();
            if (inc < size2) {
                if (entriesEqualChecker.test(o, entries2.get(inc))) {
                    count.incrementAndGet();
                } else if (inc > 0) {
                    count.set(0);
                }
            }
        });

        found = count.get();
    }

    return not ^ (found == size2);
}

From source file:org.loklak.susi.SusiRule.java

/**
 * The score is used to prefer one rule over another if that other rule has a lower score.
 * The reason that this score is used is given by the fact that we need rules which have
 * fuzzy phrase definitions and several rules might be selected because these fuzzy phrases match
 * on the same input sequence. One example is the catch-all rule which fires always but has
 * lowest priority.//from   w w w .j  av  a 2s .  com
 * In the context of artificial mind modeling the score plays the role of a positive emotion.
 * If the AI learns that a rule was applied and caused a better situation (see also: game playing gamefield
 * evaluation) then the rule might get the score increased. Having many rules which have a high score
 * therefore might induce a 'good feeling' because it is known that the outcome will be good.
 * @return a score which is used for sorting of the rules. The higher the better. Highest score wins.
 */
public int getScore() {

    if (this.score >= 0)
        return this.score;

    /*
     * Score Computation:
     * see: https://github.com/loklak/loklak_server/issues/767
            
     * (1) primary criteria is the conversation plan:
     * purpose: {answer, question, reply} purpose would have to be defined
     * The purpose can be computed using a pattern on the answer expression: is there a '?' at the end, is it a question. Is there also a '. ' (end of sentence) in the text, is it a reply.
            
     * (2) secondary criteria is the existence of a pattern where we decide between prior and minor rules
     * pattern: {false, true} with/without pattern could be computed from the rule string
     * all rules with pattern are ordered in the middle between prior and minor
     * this is combined with
     * prior: {false, true} overruling (prior=true) or default (prior=false) would have to be defined
     * The prior attribute can also be expressed as an replacement of a pattern type because it is only relevant if the query is not a pattern or regular expression.
     * The resulting criteria is a property with three possible values: {minor, pattern, major}
            
     * (3) tertiary criteria is the operation type
     * op: {retrieval, computation, storage} the operation could be computed from the rule string
            
     * (4) quaternary criteria is the IO activity (-location)
     * io: {remote, local, ram} the storage location can be computed from the rule string
            
     * (5) the meatsize (number of characters that are non-patterns)
            
     * (6) finally the subscore can be assigned manually
     * subscore a score in a small range which can be used to distinguish rules within the same categories
     */

    // extract the score
    this.score = 0;

    // (1) conversation plan from the answer purpose
    final AtomicInteger dialogType_subscore = new AtomicInteger(0);
    this.actions.forEach(action -> dialogType_subscore
            .set(Math.max(dialogType_subscore.get(), action.getDialogType().getSubscore())));
    this.score = this.score * SusiAction.DialogType.values().length + dialogType_subscore.get();

    // (2) pattern score
    final AtomicInteger phrases_subscore = new AtomicInteger(0);
    this.phrases
            .forEach(phrase -> phrases_subscore.set(Math.max(phrases_subscore.get(), phrase.getSubscore())));
    this.score = this.score * SusiPhrase.Type.values().length + phrases_subscore.get();

    // (3) operation type - there may be no operation at all
    final AtomicInteger inference_subscore = new AtomicInteger(0);
    this.inferences.forEach(inference -> inference_subscore
            .set(Math.max(inference_subscore.get(), inference.getType().getSubscore())));
    this.score = this.score * (1 + SusiInference.Type.values().length) + inference_subscore.get();

    // (4) meatsize
    final AtomicInteger phrases_meatscore = new AtomicInteger(0);
    this.phrases
            .forEach(phrase -> phrases_meatscore.set(Math.max(phrases_meatscore.get(), phrase.getMeatsize())));
    this.score = this.score * 100 + phrases_meatscore.get();

    // (6) subscore from the user
    this.score += this.score * 1000 + Math.min(1000, this.user_subscore);

    /*
    System.out.println("DEBUG RULE SCORE: id=" + this.id + ", score=" + this.score +
        ", dialog=" + dialogType_subscore.get() +
        ", phrase=" + phrases_subscore.get() +
        ", inference=" + inference_subscore.get() +
        ", meatscore=" + phrases_meatscore.get() +
        ", subscore=" + user_subscore +
        ", pattern=" +phrases.get(0).toString() + (this.inferences.size() > 0 ? ", inference=" + this.inferences.get(0).getExpression() : ""));
    */
    return this.score;
}

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

@Override
public void createTable(final HTableDescriptor desc, byte[][] splitKeys) throws IOException {
    try {/*  ww w. ja  va2 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");
}