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:org.apache.tinkerpop.gremlin.groovy.engine.GremlinExecutorTest.java

@Test
public void shouldEvalInMultipleThreads() throws Exception {
    final GremlinExecutor gremlinExecutor = GremlinExecutor.build().create();

    final CyclicBarrier barrier = new CyclicBarrier(2);
    final AtomicInteger i1 = new AtomicInteger(0);
    final AtomicBoolean b1 = new AtomicBoolean(false);
    final Thread t1 = new Thread(() -> {
        try {//w ww  .j a  v  a  2 s.  co m
            barrier.await();
            i1.set((Integer) gremlinExecutor.eval("1+1").get());
        } catch (Exception ex) {
            b1.set(true);
        }
    });

    final AtomicInteger i2 = new AtomicInteger(0);
    final AtomicBoolean b2 = new AtomicBoolean(false);
    final Thread t2 = new Thread(() -> {
        try {
            barrier.await();
            i2.set((Integer) gremlinExecutor.eval("1+1").get());
        } catch (Exception ex) {
            b2.set(true);
        }
    });

    t1.start();
    t2.start();

    t1.join();
    t2.join();

    assertEquals(2, i1.get());
    assertEquals(2, i2.get());
    assertFalse(b1.get());
    assertFalse(b2.get());

    gremlinExecutor.close();
}

From source file:org.zenoss.zep.index.impl.EventIndexerImpl.java

private int doIndex(long throughTime) throws ZepException {
    final EventPostIndexContext context = new EventPostIndexContext() {
        @Override/*www  .j  a v a  2  s.  c om*/
        public boolean isArchive() {
            return !isSummary;
        }
    };
    final List<EventPostIndexPlugin> plugins = this.pluginService.getPluginsByType(EventPostIndexPlugin.class);
    final AtomicBoolean calledStartBatch = new AtomicBoolean();
    final List<Long> indexQueueIds = queueDao.indexEvents(new EventIndexHandler() {
        @Override
        public void handle(EventSummary event) throws Exception {
            indexDao.stage(event);
            if (shouldRunPostprocessing(event)) {
                boolean shouldStartBatch = calledStartBatch.compareAndSet(false, true);
                for (EventPostIndexPlugin plugin : plugins) {
                    try {
                        if (shouldStartBatch) {
                            plugin.startBatch(context);
                        }
                        plugin.processEvent(event, context);
                    } catch (Exception e) {
                        // Post-processing plug-in failures are not fatal errors.
                        logger.warn("Failed to run post-processing plug-in on event: " + event, e);
                    }
                }
            }
        }

        @Override
        public void handleDeleted(String uuid) throws Exception {
            indexDao.stageDelete(uuid);
        }

        @Override
        public void handleComplete() throws Exception {
            if (calledStartBatch.get()) {
                for (EventPostIndexPlugin plugin : plugins) {
                    plugin.endBatch(context);
                }
            }
            indexDao.commit();
        }
    }, limit, throughTime);

    if (!indexQueueIds.isEmpty()) {
        logger.debug("Completed indexing {} events on {}", indexQueueIds.size(), indexDao.getName());
        try {
            DaoUtils.deadlockRetry(new Callable<Integer>() {
                @Override
                public Integer call() throws Exception {
                    return queueDao.deleteIndexQueueIds(indexQueueIds);
                }
            });
        } catch (ZepException e) {
            throw e;
        } catch (Exception e) {
            throw new ZepException(e.getLocalizedMessage(), e);
        }
    }
    return indexQueueIds.size();
}

From source file:com.microsoft.tfs.core.clients.versioncontrol.internal.localworkspace.WorkspaceVersionTable.java

public ServerItemLocalVersionUpdate[] getUpdatesForReconcile(final LocalPendingChange[] pendingChanges,
        final boolean reconcileMissingOnDisk, final AtomicBoolean outClearLocalVersionTable) {
    // Start out by presuming we are going to clear the local version table
    outClearLocalVersionTable.set(true);

    final Set<ServerItemLocalVersionUpdate> updates = new HashSet<ServerItemLocalVersionUpdate>();

    // Add an update for every row in the table which is marked
    // PendingReconcile.
    final Iterable<WorkspaceLocalItemPair> pairs = server.EnumSubTreeReferencedObjects(ServerPath.ROOT,
            EnumSubTreeOptions.ENUMERATE_SUB_TREE_ROOT, Integer.MAX_VALUE);

    for (final WorkspaceLocalItemPair pair : pairs) {
        if (pair.getCommitted() != null) {
            if (outClearLocalVersionTable.get() && !pair.getCommitted().isPendingReconcile()) {
                // There's a row in our local table which has been
                // reconciled. So this is not a recovery situation where the
                // local version table has been lost locally. Don't clear
                // the local version table as a part of this reconcile.
                outClearLocalVersionTable.set(false);
            }/*from  w w  w.j ava  2 s  .  c  om*/

            final ServerItemLocalVersionUpdate update = pair.getCommitted()
                    .getLocalVersionUpdate(reconcileMissingOnDisk);

            if (null != update) {
                updates.add(update);
            }
        }

        if (pair.getUncommitted() != null) {
            if (outClearLocalVersionTable.get() && !pair.getUncommitted().isPendingReconcile()) {
                // There's a row in our local table which has been
                // reconciled. So this is not a recovery situation where the
                // local version table has been lost locally. Don't clear
                // the local version table as a part of this reconcile.
                outClearLocalVersionTable.set(false);
            }

            final ServerItemLocalVersionUpdate update = pair.getUncommitted()
                    .getLocalVersionUpdate(reconcileMissingOnDisk);

            if (null != update) {
                updates.add(update);
            }
        }
    }

    // Next, add an update for every item which is in the removed items
    // list.
    for (final WorkspaceLocalItem lvEntry : removedItems) {
        // Make sure that the item has not been resurrected in the local
        // version table.
        if (null == getByServerItem(lvEntry.getServerItem(), lvEntry.isCommitted())) {
            updates.add(lvEntry.getLocalVersionUpdate());
        }
    }

    // For safety, always enqueue local version updates for pending changes.
    for (final LocalPendingChange pc : pendingChanges) {
        final WorkspaceLocalItem lvEntry = getByServerItem(
                pc.isCommitted() ? pc.getCommittedServerItem() : pc.getTargetServerItem(), pc.isCommitted());

        if (lvEntry != null) {
            if (!lvEntry.isPendingReconcile()) {
                lvEntry.setPendingReconcile(true);
                pendingReconcileCount++;
            }

            updates.add(lvEntry.getLocalVersionUpdate(reconcileMissingOnDisk));
        }
    }

    return updates.toArray(new ServerItemLocalVersionUpdate[updates.size()]);

}

From source file:nlp.mediawiki.parser.MultistreamBzip2XmlDumpParser.java

@Override
public void run() {
    final AtomicBoolean terminate = new AtomicBoolean(false);
    final Logger logger = LoggerFactory.getLogger(MultistreamBzip2XmlDumpParser.class);
    //1. Start all worker threads
    for (int i = 0; i < workers.length; i++) {
        workers[i] = new Worker();
        workers[i].setName("Dump Worker " + i);
    }/*from  w  w  w .  j a  v  a 2 s. c  om*/

    //Add an uncaught exception handler and allow for a graceful shutdown.
    Thread.UncaughtExceptionHandler h = new Thread.UncaughtExceptionHandler() {
        public void uncaughtException(Thread th, Throwable ex) {
            logger.error("Fatal error in thread {}, terminating...", th.getName(), ex);
            for (Worker worker : workers) {
                worker.interrupt();
            }
            terminate.set(true);
        }
    };

    for (Worker worker : workers) {
        worker.setUncaughtExceptionHandler(h);
        worker.start();
    }

    //2. Seed them with data until there is no more
    PageBlock data;
    while ((data = pageReader.next()) != null && !terminate.get()) {
        try {
            blocks.put(data);
        } catch (InterruptedException e) {
            logger.error("Data put interrupted", e);
            break;
        }
    }

    for (int i = 0; i < workers.length; i++) {
        try {
            blocks.put(new PageBlock(null, null));
        } catch (InterruptedException e) {
            logger.info("Termination interrupted", e);
            break;
        }
    }

    //3. Await termination of all workers
    for (Worker worker : workers) {
        try {
            worker.join();
        } catch (InterruptedException e) {
            logger.error("Worker {} thread interrupted.", worker.getName(), e);
        }
    }

    output(Collections.<Page>emptyList());
}

From source file:com.gargoylesoftware.js.CodeStyleTest.java

private boolean isSvnPropertiesDefined(final File file) {
    try {//from   ww w . j  a v  a  2s.c  o m
        final AtomicBoolean eol = new AtomicBoolean();
        svnWCClient_.doGetProperty(file, null, SVNRevision.WORKING, SVNRevision.WORKING, SVNDepth.EMPTY,
                new ISVNPropertyHandler() {

                    @Override
                    public void handleProperty(final long revision, final SVNPropertyData property) {
                        // nothing to do
                    }

                    @Override
                    public void handleProperty(final SVNURL url, final SVNPropertyData property) {
                        // nothing to do
                    }

                    @Override
                    public void handleProperty(final File path, final SVNPropertyData property) {
                        final String name = property.getName();
                        final String value = property.getValue().getString();
                        if ("svn:eol-style".equals(name) && "native".equals(value)) {
                            eol.set(true);
                        }
                    }
                }, null);

        final String fileName = file.getName().toLowerCase(Locale.ROOT);

        for (final String extension : EOL_EXTENSIONS_) {
            if (fileName.endsWith(extension)) {
                return eol.get();
            }
        }
        return true;
    } catch (final Exception e) {
        //nothing
    }
    final String path = file.getAbsolutePath();
    // automatically generated and is outside SVN control
    return (path.contains("jQuery") && path.contains("WEB-INF") && path.contains("cgi"))
            || (path.contains("jQuery") && path.contains("csp.log"));
}

From source file:cc.gospy.example.google.GoogleScholarSpider.java

public Collection<String> getResultLinks(final String keyword, final int pageFrom, final int pageTo) {
    if (pageFrom < 1)
        throw new IllegalArgumentException(pageFrom + "<" + 1);
    if (pageFrom >= pageTo)
        throw new IllegalArgumentException(pageFrom + ">=" + pageTo);

    final AtomicInteger currentPage = new AtomicInteger(pageFrom);
    final AtomicBoolean returned = new AtomicBoolean(false);
    final Collection<String> links = new LinkedHashSet<>();
    Gospy googleScholarSpider = Gospy.custom()
            .setScheduler(//from   w w  w.  jav a2s  .co m
                    Schedulers.VerifiableScheduler.custom().setExitCallback(() -> returned.set(true)).build())
            .addFetcher(Fetchers.HttpFetcher.custom()
                    .before(request -> request.setConfig(
                            RequestConfig.custom().setProxy(new HttpHost("127.0.0.1", 8118)).build()))
                    .build())
            .addProcessor(Processors.XPathProcessor.custom().extract(
                    "//*[@id='gs_ccl_results']/div/div/h3/a/@href", (task, resultList, returnedData) -> {
                        links.addAll(resultList);
                        currentPage.incrementAndGet();
                        if (pageFrom <= currentPage.get() && currentPage.get() < pageTo) {
                            return Arrays.asList(
                                    new Task(String.format("https://scholar.google.com/scholar?start=%d&q=%s",
                                            (currentPage.get() - 1) * 10, keyword)));
                        } else {
                            return Arrays.asList();
                        }
                    }).build())
            .build()
            .addTask(String.format("https://scholar.google.com/scholar?start=%d&q=%s", pageFrom, keyword));
    googleScholarSpider.start();
    while (!returned.get())
        ; // block until spider returned
    googleScholarSpider.stop();
    return links;
}

From source file:org.eclipse.hono.application.HonoApplication.java

/**
 * Deploys all verticles the Hono server consists of.
 * //ww w .  java2 s.  c om
 * @return true if deployment was successful
 */
private boolean registerVerticles() {

    if (vertx == null) {
        throw new IllegalStateException("no Vert.x instance has been configured");
    }

    final CountDownLatch startupLatch = new CountDownLatch(1);
    final AtomicBoolean startupSucceeded = new AtomicBoolean(false);

    // without creating a first instance here, deployment of the HonoServer verticles fails
    // TODO: find out why
    HonoServer firstInstance = serverFactory.getHonoServer();

    final int instanceCount = honoConfig.getMaxInstances();

    Future<Void> started = Future.future();
    started.setHandler(ar -> {
        if (ar.failed()) {
            LOG.error("cannot start up HonoServer", ar.cause());
        } else {
            startupSucceeded.set(true);
        }
        startupLatch.countDown();
    });

    CompositeFuture.all(deployAuthenticationService(), // we only need 1 authentication service
            deployAuthorizationService(), // we only need 1 authorization service
            deployCredentialsService(), deployRegistrationService()).setHandler(ar -> {
                if (ar.succeeded()) {
                    deployServer(firstInstance, instanceCount, started);
                } else {
                    started.fail(ar.cause());
                }
            });

    try {
        if (startupLatch.await(honoConfig.getStartupTimeout(), TimeUnit.SECONDS)) {
            if (startupSucceeded.get()) {
                LOG.info("Hono startup completed successfully");
            } else {
                shutdown();
            }
        } else {
            LOG.error("startup timed out after {} seconds, shutting down ...", honoConfig.getStartupTimeout());
            shutdown();
            startupSucceeded.set(false);
        }
    } catch (InterruptedException e) {
        LOG.error("startup process has been interrupted, shutting down ...");
        Thread.currentThread().interrupt();
        shutdown();
        startupSucceeded.set(false);
    }
    return startupSucceeded.get();
}

From source file:io.atomix.protocols.gossip.map.AntiEntropyMapDelegate.java

private MapValue removeInternal(String key, Optional<byte[]> value, Optional<MapValue> tombstone) {
    checkState(!closed, destroyedMessage);
    checkNotNull(key, ERROR_NULL_KEY);//from  ww w  .  ja  v a 2 s . c o  m
    checkNotNull(value, ERROR_NULL_VALUE);
    tombstone.ifPresent(v -> checkState(v.isTombstone()));

    counter.incrementCount();
    AtomicBoolean updated = new AtomicBoolean(false);
    AtomicReference<MapValue> previousValue = new AtomicReference<>();
    items.compute(key, (k, existing) -> {
        boolean valueMatches = true;
        if (value.isPresent() && existing != null && existing.isAlive()) {
            valueMatches = Arrays.equals(value.get(), existing.get());
        }
        if (existing == null) {
            log.trace("ECMap Remove: Existing value for key {} is already null", k);
        }
        if (valueMatches) {
            if (existing == null) {
                updated.set(tombstone.isPresent());
            } else {
                updated.set(!tombstone.isPresent() || tombstone.get().isNewerThan(existing));
            }
        }
        if (updated.get()) {
            previousValue.set(existing);
            return tombstone.orElse(null);
        } else {
            return existing;
        }
    });
    return previousValue.get();
}

From source file:org.apache.tinkerpop.gremlin.server.GremlinServerIntegrateTest.java

@Test
public void shouldRespectHighWaterMarkSettingAndSucceed() throws Exception {
    // the highwatermark should get exceeded on the server and thus pause the writes, but have no problem catching
    // itself up - this is a tricky tests to get passing on all environments so this assumption will deny the
    // test for most cases
    assumeThat("Set the 'assertNonDeterministic' property to true to execute this test",
            System.getProperty("assertNonDeterministic"), is("true"));

    final Cluster cluster = Cluster.open();
    final Client client = cluster.connect();

    try {/*from   w  w  w  .  j a v a 2 s  .com*/
        final int resultCountToGenerate = 1000;
        final int batchSize = 3;
        final String fatty = IntStream.range(0, 175).mapToObj(String::valueOf).collect(Collectors.joining());
        final String fattyX = "['" + fatty + "'] * " + resultCountToGenerate;

        // don't allow the thread to proceed until all results are accounted for
        final CountDownLatch latch = new CountDownLatch(resultCountToGenerate);
        final AtomicBoolean expected = new AtomicBoolean(false);
        final AtomicBoolean faulty = new AtomicBoolean(false);
        final RequestMessage request = RequestMessage.build(Tokens.OPS_EVAL)
                .addArg(Tokens.ARGS_BATCH_SIZE, batchSize).addArg(Tokens.ARGS_GREMLIN, fattyX).create();

        client.submitAsync(request).thenAcceptAsync(r -> {
            r.stream().forEach(item -> {
                try {
                    final String aFattyResult = item.getString();
                    expected.set(aFattyResult.equals(fatty));
                } catch (Exception ex) {
                    ex.printStackTrace();
                    faulty.set(true);
                } finally {
                    latch.countDown();
                }
            });
        });

        assertTrue(latch.await(30000, TimeUnit.MILLISECONDS));
        assertEquals(0, latch.getCount());
        assertFalse(faulty.get());
        assertTrue(expected.get());

        assertTrue(recordingAppender.getMessages().stream()
                .anyMatch(m -> m.contains("Pausing response writing as writeBufferHighWaterMark exceeded on")));
    } catch (Exception ex) {
        fail("Shouldn't have tossed an exception");
    } finally {
        cluster.close();
    }
}

From source file:eu.europa.ec.markt.dss.validation102853.pades.PAdESSignature.java

private boolean hasDSSDictionary() {
    boolean hasDSSDictionary;
    final PDFSignatureService pdfTimestampSignatureService = PdfObjFactory.getInstance()
            .newTimestampSignatureService();
    try {//from   ww  w.  j a v a2 s  .  c o  m
        final AtomicBoolean atomicHasDSSDictionnary = new AtomicBoolean(false);
        pdfTimestampSignatureService.validateSignatures(document.openStream(),
                new SignatureValidationCallback() {
                    @Override
                    public void validate(PdfDict catalog, PdfDict outerCatalog, X509Certificate signingCert,
                            Date signingDate, Certificate[] certs, PdfDict signatureDictionary,
                            PdfSignatureInfo pk) {
                        PdfDict _catalog = outerCatalog != null ? outerCatalog : pdfCatalog;
                        if (_catalog != null) {
                            atomicHasDSSDictionnary.set((getCertificateSource() != null)
                                    && (getCertificateSource().getCertificates() != null)
                                    && (!getCertificateSource().getCertificates().isEmpty()));
                        }
                    }
                });
        hasDSSDictionary = atomicHasDSSDictionnary.get();
    } catch (IOException e) {
        throw new DSSException(e);
    } catch (SignatureException e) {
        throw new DSSException(e);
    }
    return hasDSSDictionary;
}