Example usage for java.util.concurrent.atomic AtomicBoolean get

List of usage examples for java.util.concurrent.atomic AtomicBoolean get

Introduction

In this page you can find the example usage for java.util.concurrent.atomic AtomicBoolean get.

Prototype

public final boolean get() 

Source Link

Document

Returns the current value, with memory effects as specified by VarHandle#getVolatile .

Usage

From source file:ai.susi.mind.SusiSkill.java

/**
 * if no keys are given, we compute them from the given phrases
 * @param phrases/*from w w  w. ja  v  a 2s  .co  m*/
 * @return
 */
private static JSONArray computeKeysFromPhrases(List<SusiPhrase> phrases) {
    Set<String> t = new LinkedHashSet<>();

    // create a list of token sets from the phrases
    List<Set<String>> ptl = new ArrayList<>();
    final AtomicBoolean needsCatchall = new AtomicBoolean(false);
    phrases.forEach(phrase -> {
        Set<String> s = new HashSet<>();
        for (String token : SPACE_PATTERN.split(phrase.getPattern().toString())) {
            String m = SusiPhrase.extractMeat(token.toLowerCase());
            if (m.length() > 1)
                s.add(m);
        }
        // if there is no meat inside, it will not be possible to access the skill without the catchall skill, so remember that
        if (s.size() == 0)
            needsCatchall.set(true);

        ptl.add(s);
    });

    // this is a kind of emergency case where we need a catchall skill because otherwise we cannot access one of the phrases
    JSONArray a = new JSONArray();
    if (needsCatchall.get())
        return a.put(CATCHALL_KEY);

    // collect all token
    ptl.forEach(set -> set.forEach(token -> t.add(token)));

    // if no tokens are available, return the catchall key
    if (t.size() == 0)
        return a.put(CATCHALL_KEY);

    // make a copy to make it possible to use the original key set again
    Set<String> tc = new LinkedHashSet<>();
    t.forEach(c -> tc.add(c));

    // remove all token that do not appear in all phrases
    ptl.forEach(set -> {
        Iterator<String> i = t.iterator();
        while (i.hasNext())
            if (!set.contains(i.next()))
                i.remove();
    });

    // if no token is left, use the original tc set and add all keys
    if (t.size() == 0) {
        tc.forEach(c -> a.put(c));
        return a;
    }

    // use only the first token, because that appears in all the phrases
    return new JSONArray().put(t.iterator().next());
}

From source file:io.pravega.controller.eventProcessor.impl.SerializedRequestHandlerTest.java

private void runBackgroundStreamProcessing(String streamName,
        SerializedRequestHandler<TestEvent> requestHandler, AtomicBoolean stop) {
    CompletableFuture.runAsync(() -> {
        while (!stop.get()) {
            TestEvent event = new TestEvent("scope", streamName, 0);
            event.complete();/*  ww  w  .  j  a  v a  2  s .com*/
            Futures.await(requestHandler.process(event));
        }
    });
}

From source file:de.tbuchloh.kiskis.cracker.PasswordCracker.java

public String crackPassword() {
    final Long totalEstimation = _passwordCreator.estimateTotalCount();
    _progressListener.notifyTotalCount(totalEstimation);
    _progressListener.notifyStartTime(System.currentTimeMillis());

    final AtomicBoolean found = new AtomicBoolean(false);
    final Callable<String> callable = new Callable<String>() {

        @Override/* ww w. j  a  v a 2  s . co m*/
        public String call() throws Exception {
            String guess;
            while (!found.get() && (guess = _passwordCreator.create()) != null) {
                _progressListener.notifyTry(guess);
                if (_tester.test(guess)) {
                    found.set(true);
                    return guess;
                }
            }
            return null;
        }
    };

    final int cpus = ManagementFactory.getOperatingSystemMXBean().getAvailableProcessors();
    LOG.info(String.format("Found %1$d cpus ...", cpus));
    final ExecutorService threadPool = Executors.newFixedThreadPool(cpus);
    final Collection<Callable<String>> tasks = new ArrayList<Callable<String>>();
    for (int i = 0; i < cpus; ++i) {
        tasks.add(callable);
    }
    try {
        final List<Future<String>> futures = threadPool.invokeAll(tasks);
        for (final Future<String> future : futures) {
            final String guessedPwd = future.get();
            if (guessedPwd != null) {
                return guessedPwd;
            }
        }
        return null;
    } catch (final InterruptedException e) {
        throw new KisKisRuntimeException("InterruptedException", e);
    } catch (final ExecutionException e) {
        throw new KisKisRuntimeException("ExecutionException", e);
    }
}

From source file:io.spring.initializr.web.support.SpringBootMetadataReaderTests.java

@Test
public void readAvailableVersions() throws IOException {
    this.server.expect(requestTo("https://spring.io/project_metadata/spring-boot")).andRespond(
            withSuccess(new ClassPathResource("metadata/sagan/spring-boot.json"), MediaType.APPLICATION_JSON));
    List<DefaultMetadataElement> versions = new SpringBootMetadataReader(this.objectMapper, this.restTemplate,
            this.metadata.getConfiguration().getEnv().getSpringBootMetadataUrl()).getBootVersions();
    assertThat(versions).as("spring boot versions should not be null").isNotNull();
    AtomicBoolean defaultFound = new AtomicBoolean(false);
    versions.forEach((it) -> {// ww  w.  j av a 2 s  .c om
        assertThat(it.getId()).as("Id must be set").isNotNull();
        assertThat(it.getName()).as("Name must be set").isNotNull();
        if (it.isDefault()) {
            if (defaultFound.get()) {
                fail("One default version was already found " + it.getId());
            }
            defaultFound.set(true);
        }
    });
    this.server.verify();
}

From source file:de.speexx.jira.jan.command.issuequery.CsvCreator.java

public void printIssueData(final IssueData issueData, final List<FieldName> historyFieldNames,
        final List<FieldNamePath> currentFieldNames, final TemporalChangeOutput temporalOutput,
        final AtomicBoolean header) {
    checkParameter(issueData, historyFieldNames, currentFieldNames, temporalOutput, header);

    if (header.get()) {
        printHeader(currentFieldNames, historyFieldNames, temporalOutput);
        header.set(false);//  w  w  w.  j  a v a 2s. c o m
    }

    printIssueData(issueData, currentFieldNames, historyFieldNames, temporalOutput);
}

From source file:fr.inria.oak.paxquery.pact.io.XmlConsTreePatternOutputFormat.java

private boolean allNullUnderNode(AtomicBoolean[] nullResults) {
    if (nullResults == null) {
        return false;
    }/*from   ww w .  ja va  2s .  com*/

    for (AtomicBoolean nullResult : nullResults) {
        if (!nullResult.get()) {
            return false;
        }
    }

    return true;
}

From source file:com.alexholmes.hdfsslurper.Slurper.java

private void run() throws IOException, InterruptedException {

    FileSystemManager fileSystemManager = new FileSystemManager(config);

    log.info("event#Moving any files in work directory to error directory");

    fileSystemManager.moveWorkFilesToError();

    final List<WorkerThread> workerThreads = new ArrayList<WorkerThread>();
    for (int i = 1; i <= config.getNumThreads(); i++) {
        WorkerThread t = new WorkerThread(config, fileSystemManager, TimeUnit.MILLISECONDS, i);
        t.start();//w  ww.java 2 s .com
        workerThreads.add(t);
    }

    final AtomicBoolean programmaticShutdown = new AtomicBoolean(false);

    Runtime.getRuntime().addShutdownHook(new Thread() {
        public void run() {
            try {
                if (programmaticShutdown.get()) {
                    log.info("event#JVM shutting down");
                } else {
                    log.info("event#External process signalled JVM shutdown, shutting down threads.");
                    log.info("event#This may take a few minutes until we let the threads complete ");
                    log.info("event#the current file being copied.");
                    for (WorkerThread workerThread : workerThreads) {
                        workerThread.shutdown();
                    }
                    log.info("event#Threads dead");
                }
            } catch (Throwable t) {
                log.error("event#Hit snag in shutdown hook", t);
            }

        }
    });

    log.info("event#Running");

    for (WorkerThread workerThread : workerThreads) {
        workerThread.join();
    }
    programmaticShutdown.set(true);
}

From source file:io.github.jeddict.jpa.modeler.properties.convert.ConvertPanel.java

@Override
public Convert getValue() {
    AtomicBoolean validated = new AtomicBoolean(false);
    importAttributeConverter(converter_EditorPane.getText(), validated, modelerFile);
    if (!validated.get()) {
        throw new IllegalStateException();
    }/*from  ww  w.ja  v  a 2  s  .co m*/
    convert.setConverter(converter_EditorPane.getText());
    convert.setAttributeName(null);
    convert.setDisableConversion(disableConversion_CheckBox.isSelected());
    return convert;
}

From source file:com.epam.reportportal.spock.SpockReporterTest.java

@Test
public void handleRpException() throws IllegalAccessException {
    spockReporter.handleRpException(new RestEndpointIOException(""), "");

    AtomicBoolean rpIsDown = (AtomicBoolean) readField(spockReporter, "rpIsDown", true);
    assertThat(rpIsDown.get(), is(true));
}

From source file:org.alfresco.reporting.cron.HarvestingJob.java

@Override
public void execute(JobExecutionContext context) throws JobExecutionException {
    JobDataMap jobData = context.getJobDetail().getJobDataMap();
    this.jobLockService = (JobLockService) jobData.get("jobLockService");

    logger.debug("jobLockService hashcode=" + jobLockService.hashCode());

    // get a token for a minute
    String lockToken = getLock(getLockKey(), 60000);
    if (lockToken == null) {
        return;/*from  w w w .  ja  v  a 2s  . c  o  m*/
    }
    // Use a flag to keep track of the running job
    final AtomicBoolean running = new AtomicBoolean(true);
    jobLockService.refreshLock(lockToken, lock, 30000, new JobLockRefreshCallback() {
        @Override
        public boolean isActive() {
            return running.get();
        }

        @Override
        public void lockReleased() {
            running.set(false);
        }
    });
    try {
        logger.debug("Start executeImpl");
        executeImpl(running, context);
        logger.debug("End executeImpl");
    } catch (RuntimeException e) {
        throw e;
    } finally {
        // The lock will self-release if answer isActive in the negative
        running.set(false);
        jobLockService.releaseLock(lockToken, getLockKey());
        logger.debug("Released the lock");
    }
}