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

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

Introduction

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

Prototype

public final boolean getAndSet(boolean newValue) 

Source Link

Document

Atomically sets the value to newValue and returns the old value, with memory effects as specified by VarHandle#getAndSet .

Usage

From source file:Main.java

public static void main(String[] argv) throws Exception {
    AtomicBoolean atomicBoolean = new AtomicBoolean();

    System.out.println(atomicBoolean.getAndSet(true));
}

From source file:com.blockhaus2000.csvviewer.CsvViewerMain.java

public static void main(final String[] args) {
    try (final CSVParser parser = new CSVParser(new InputStreamReader(System.in), CSVFormat.DEFAULT)) {
        final Table table = new Table();

        final Map<String, Integer> headerMap = parser.getHeaderMap();
        if (headerMap != null) {
            final TableRow headerRow = new TableRow();
            headerMap.keySet().forEach(headerData -> headerRow.addCell(new TableRowCell(headerData)));
            table.setHeaderRow(headerRow);
        }//from   ww w.  j  av a  2s .  co m

        final AtomicBoolean asHeader = new AtomicBoolean(headerMap == null);
        parser.getRecords().forEach(record -> {
            final TableRow row = new TableRow();
            record.forEach(rowData -> row.addCell(new TableRowCell(rowData)));
            if (asHeader.getAndSet(false)) {
                table.setHeaderRow(row);
            } else {
                table.addRow(row);
            }
        });

        System.out.println(table.getFormattedString());
    } catch (final IOException cause) {
        throw new RuntimeException("An error occurred whilst parsing stdin!", cause);
    }
}

From source file:org.normandra.CassandraTestUtil.java

public static void start(final String yamlFile) throws Exception {
    if (embedded != null) {
        return;/* w ww .  j a v  a  2 s.  c o  m*/
    }

    log4j(false);

    final File embeddedDir = new File("target/embeddedCassandra").getCanonicalFile();
    final File tmpYaml = new File(embeddedDir, FilenameUtils.getName(yamlFile));
    if (tmpYaml.exists()) {
        FileUtils.forceDelete(tmpYaml);
    }
    if (embeddedDir.exists()) {
        FileUtils.deleteDirectory(embeddedDir);
    }
    FileUtils.copyURLToFile(CassandraTestUtil.class.getResource(yamlFile), tmpYaml);

    System.setProperty("cassandra.config", tmpYaml.getCanonicalFile().toURI().toString());
    System.setProperty("cassandra-foreground", "true");

    clearAndReset();

    if (null == embedded) {
        final AtomicBoolean started = new AtomicBoolean(false);
        embedded = new EmbeddedCassandraService();
        final Runnable worker = new Runnable() {
            @Override
            public void run() {
                try {
                    embedded.start();
                    started.getAndSet(true);
                } catch (final Exception e) {
                    logger.warn("Unable to start embedded cassandra server.", e);
                }
            }
        };
        final Thread thread = new Thread(worker);
        thread.setDaemon(true);
        thread.setName(CassandraTestUtil.class.getSimpleName() + "[embedded]");
        thread.start();

        for (int i = 0; i < 60; i++) {
            if (started.get()) {
                break;
            }
            Thread.sleep(250);
        }
    }
}

From source file:org.sonar.server.component.index.ComponentIndexSearchFeature.java

protected BoolQueryBuilder prefixAndPartialQuery(String queryText, String fieldName) {
    BoolQueryBuilder query = boolQuery();

    AtomicBoolean first = new AtomicBoolean(true);
    split(queryText).map(queryTerm -> {

        if (first.getAndSet(false)) {
            return prefixQuery(fieldName, queryTerm);
        }/* w  ww  .  j a  va  2 s. com*/

        return partialTermQuery(queryTerm);
    }).forEach(query::must);
    return query;
}

From source file:org.sonar.server.es.textsearch.ComponentTextSearchFeature.java

protected BoolQueryBuilder prefixAndPartialQuery(String queryText, String fieldName, String originalFieldName) {
    BoolQueryBuilder queryBuilder = boolQuery();

    AtomicBoolean first = new AtomicBoolean(true);
    split(queryText).map(queryTerm -> {

        if (first.getAndSet(false)) {
            return prefixQuery(fieldName, queryTerm);
        }//from w w  w . ja v  a 2  s . c om

        return partialTermQuery(queryTerm, originalFieldName);
    }).forEach(queryBuilder::must);
    return queryBuilder;
}

From source file:org.sonar.server.es.textsearch.ComponentTextSearchFeatureRepertoire.java

protected BoolQueryBuilder prefixAndPartialQuery(List<String> tokens, String originalFieldName,
        DefaultIndexSettingsElement analyzer) {
    BoolQueryBuilder queryBuilder = boolQuery();
    AtomicBoolean first = new AtomicBoolean(true);
    tokens.stream().map(queryTerm -> {

        if (first.getAndSet(false)) {
            return tokenQuery(queryTerm, originalFieldName, analyzer);
        }//from  w w  w  . j  a  va  2s  . c  om

        return tokenQuery(queryTerm, originalFieldName, SEARCH_GRAMS_ANALYZER);
    }).forEach(queryBuilder::must);
    return queryBuilder;
}

From source file:info.archinnov.achilles.it.TestNativeQueries.java

@Test
public void should_iterate_regular_typed_query() throws Exception {
    //Given/*from w w  w.j  a  va  2  s.c  om*/
    final Map<String, Object> values = new HashMap<>();
    final long id = RandomUtils.nextLong(0L, Long.MAX_VALUE);
    values.put("id", id);
    values.put("date1", "'2015-10-01 00:00:00+0000'");
    values.put("date2", "'2015-10-02 00:00:00+0000'");
    values.put("date3", "'2015-10-03 00:00:00+0000'");
    values.put("date4", "'2015-10-04 00:00:00+0000'");
    values.put("date5", "'2015-10-05 00:00:00+0000'");
    values.put("date6", "'2015-10-06 00:00:00+0000'");
    values.put("date7", "'2015-10-07 00:00:00+0000'");
    values.put("date8", "'2015-10-08 00:00:00+0000'");
    values.put("date9", "'2015-10-09 00:00:00+0000'");
    scriptExecutor.executeScriptTemplate("SimpleEntity/insert_many_rows.cql", values);

    final SimpleStatement statement = new SimpleStatement("SELECT * FROM simple WHERE id = :id LIMIT 100");

    //When
    final Iterator<TypedMap> iter = manager.query().nativeQuery(statement, id).iterator();

    //Then
    final AtomicBoolean foundEntity = new AtomicBoolean(false);
    iter.forEachRemaining(instance -> {
        foundEntity.getAndSet(true);
        assertThat(instance).isNotNull();
        assertThat(instance.<String>getTyped("value")).contains("id - date");
    });
    assertThat(foundEntity.get()).isTrue();
}

From source file:info.archinnov.achilles.it.TestTypedQueries.java

@Test
public void should_iterate_regular_typed_query() throws Exception {
    //Given/* w w  w.  ja va  2 s .c  om*/
    final Map<String, Object> values = new HashMap<>();
    final long id = RandomUtils.nextLong(0L, Long.MAX_VALUE);
    values.put("id", id);
    values.put("date1", "'2015-10-01 00:00:00+0000'");
    values.put("date2", "'2015-10-02 00:00:00+0000'");
    values.put("date3", "'2015-10-03 00:00:00+0000'");
    values.put("date4", "'2015-10-04 00:00:00+0000'");
    values.put("date5", "'2015-10-05 00:00:00+0000'");
    values.put("date6", "'2015-10-06 00:00:00+0000'");
    values.put("date7", "'2015-10-07 00:00:00+0000'");
    values.put("date8", "'2015-10-08 00:00:00+0000'");
    values.put("date9", "'2015-10-09 00:00:00+0000'");
    scriptExecutor.executeScriptTemplate("SimpleEntity/insert_many_rows.cql", values);

    final SimpleStatement statement = new SimpleStatement("SELECT * FROM simple WHERE id = :id LIMIT 100");

    //When
    final Iterator<SimpleEntity> iter = manager.query().typedQueryForSelect(statement, id).iterator();

    //Then
    final AtomicBoolean foundEntity = new AtomicBoolean(false);
    iter.forEachRemaining(instance -> {
        foundEntity.getAndSet(true);
        assertThat(instance).isNotNull();
        assertThat(instance.getValue()).contains("id - date");
    });

    assertThat(foundEntity.get()).isTrue();
}

From source file:io.pravega.segmentstore.server.reading.StorageReaderTests.java

/**
 * Tests the ability to queue dependent reads (subsequent reads that only want to read a part of a previous read).
 * Test this both with successful and failed reads.
 *//*w  w w . ja v a  2  s .  c o m*/
@Test
public void testDependents() {
    final Duration waitTimeout = Duration.ofSeconds(5);
    TestStorage storage = new TestStorage();
    CompletableFuture<Integer> signal = new CompletableFuture<>();
    AtomicBoolean wasReadInvoked = new AtomicBoolean();
    storage.readImplementation = () -> {
        if (wasReadInvoked.getAndSet(true)) {
            Assert.fail(
                    "Read was invoked multiple times, which is a likely indicator that the requests were not chained.");
        }
        return signal;
    };

    @Cleanup
    StorageReader reader = new StorageReader(SEGMENT_METADATA, storage, executorService());

    // Create some reads.
    CompletableFuture<StorageReader.Result> c1 = new CompletableFuture<>();
    CompletableFuture<StorageReader.Result> c2 = new CompletableFuture<>();
    reader.execute(new StorageReader.Request(0, 100, c1::complete, c1::completeExceptionally, TIMEOUT));
    reader.execute(new StorageReader.Request(50, 100, c2::complete, c2::completeExceptionally, TIMEOUT));

    Assert.assertFalse("One or more of the reads has completed prematurely.", c1.isDone() || c2.isDone());

    signal.completeExceptionally(new IntentionalException());
    AssertExtensions.assertThrows("The first read was not failed with the correct exception.",
            () -> c1.get(waitTimeout.toMillis(), TimeUnit.MILLISECONDS),
            ex -> ex instanceof IntentionalException);

    AssertExtensions.assertThrows("The second read was not failed with the correct exception.",
            () -> c2.get(waitTimeout.toMillis(), TimeUnit.MILLISECONDS),
            ex -> ex instanceof IntentionalException);
}

From source file:io.pravega.segmentstore.server.reading.StorageReadManagerTests.java

/**
 * Tests the ability to queue dependent reads (subsequent reads that only want to read a part of a previous read).
 * Test this both with successful and failed reads.
 *//*from  w  w w .  ja  v  a2s.co  m*/
@Test
public void testDependents() {
    final Duration waitTimeout = Duration.ofSeconds(5);
    TestStorage storage = new TestStorage();
    CompletableFuture<Integer> signal = new CompletableFuture<>();
    AtomicBoolean wasReadInvoked = new AtomicBoolean();
    storage.readImplementation = () -> {
        if (wasReadInvoked.getAndSet(true)) {
            Assert.fail(
                    "Read was invoked multiple times, which is a likely indicator that the requests were not chained.");
        }
        return signal;
    };

    @Cleanup
    StorageReadManager reader = new StorageReadManager(SEGMENT_METADATA, storage, executorService());

    // Create some reads.
    CompletableFuture<StorageReadManager.Result> c1 = new CompletableFuture<>();
    CompletableFuture<StorageReadManager.Result> c2 = new CompletableFuture<>();
    reader.execute(new StorageReadManager.Request(0, 100, c1::complete, c1::completeExceptionally, TIMEOUT));
    reader.execute(new StorageReadManager.Request(50, 100, c2::complete, c2::completeExceptionally, TIMEOUT));

    Assert.assertFalse("One or more of the reads has completed prematurely.", c1.isDone() || c2.isDone());

    signal.completeExceptionally(new IntentionalException());
    AssertExtensions.assertThrows("The first read was not failed with the correct exception.",
            () -> c1.get(waitTimeout.toMillis(), TimeUnit.MILLISECONDS),
            ex -> ex instanceof IntentionalException);

    AssertExtensions.assertThrows("The second read was not failed with the correct exception.",
            () -> c2.get(waitTimeout.toMillis(), TimeUnit.MILLISECONDS),
            ex -> ex instanceof IntentionalException);
}