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:io.atomix.protocols.gossip.map.AntiEntropyMapDelegate.java

private void processUpdates(Collection<UpdateEntry> updates) {
    if (closed) {
        return;//ww w . j  ava  2 s  . co  m
    }
    updates.forEach(update -> {
        final String key = update.key();
        final MapValue value = update.value() == null ? null : update.value().copy();
        if (value == null || value.isTombstone()) {
            MapValue previousValue = removeInternal(key, Optional.empty(), Optional.ofNullable(value));
            if (previousValue != null && previousValue.isAlive()) {
                notifyListeners(
                        new MapDelegateEvent<>(REMOVE, decodeKey(key), previousValue.get(this::decodeValue)));
            }
        } else {
            counter.incrementCount();
            AtomicReference<byte[]> oldValue = new AtomicReference<>();
            AtomicBoolean updated = new AtomicBoolean(false);
            items.compute(key, (k, existing) -> {
                if (existing == null || value.isNewerThan(existing)) {
                    updated.set(true);
                    oldValue.set(existing != null ? existing.get() : null);
                    return value;
                }
                return existing;
            });

            if (updated.get()) {
                if (oldValue.get() == null) {
                    notifyListeners(new MapDelegateEvent<>(INSERT, decodeKey(key), decodeValue(value.get())));
                } else {
                    notifyListeners(new MapDelegateEvent<>(UPDATE, decodeKey(key), decodeValue(value.get())));
                }
            }
        }
    });
}

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

@Test
public void shouldReturnInvalidRequestArgsWhenInvalidReservedBindingKeyIsUsed() throws Exception {
    try (SimpleClient client = new WebSocketClient()) {
        final Map<String, Object> bindings = new HashMap<>();
        bindings.put(T.id.getAccessor(), "123");
        final RequestMessage request = RequestMessage.build(Tokens.OPS_EVAL)
                .addArg(Tokens.ARGS_GREMLIN, "[1,2,3,4,5,6,7,8,9,0]").addArg(Tokens.ARGS_BINDINGS, bindings)
                .create();/*from  w  ww .  ja  v  a2s  . c o  m*/
        final CountDownLatch latch = new CountDownLatch(1);
        final AtomicBoolean pass = new AtomicBoolean(false);
        client.submit(request, result -> {
            if (result.getStatus().getCode() != ResponseStatusCode.PARTIAL_CONTENT) {
                pass.set(ResponseStatusCode.REQUEST_ERROR_INVALID_REQUEST_ARGUMENTS == result.getStatus()
                        .getCode());
                latch.countDown();
            }
        });

        if (!latch.await(3000, TimeUnit.MILLISECONDS))
            fail("Request should have returned error, but instead timed out");
        assertTrue(pass.get());
    }
}

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

@Test
public void shouldReturnInvalidRequestArgsWhenInvalidTypeBindingKeyIsUsed() throws Exception {
    try (SimpleClient client = new WebSocketClient()) {
        final Map<Object, Object> bindings = new HashMap<>();
        bindings.put(1, "123");
        final RequestMessage request = RequestMessage.build(Tokens.OPS_EVAL)
                .addArg(Tokens.ARGS_GREMLIN, "[1,2,3,4,5,6,7,8,9,0]").addArg(Tokens.ARGS_BINDINGS, bindings)
                .create();//from   w w  w.j a va 2  s  .  c  o  m
        final CountDownLatch latch = new CountDownLatch(1);
        final AtomicBoolean pass = new AtomicBoolean(false);
        client.submit(request, result -> {
            if (result.getStatus().getCode() != ResponseStatusCode.PARTIAL_CONTENT) {
                pass.set(ResponseStatusCode.REQUEST_ERROR_INVALID_REQUEST_ARGUMENTS == result.getStatus()
                        .getCode());
                latch.countDown();
            }
        });

        if (!latch.await(3000, TimeUnit.MILLISECONDS))
            fail("Request should have returned error, but instead timed out");
        assertTrue(pass.get());
    }
}

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

@Test
public void shouldReturnInvalidRequestArgsWhenInvalidNullBindingKeyIsUsed() throws Exception {
    try (SimpleClient client = new WebSocketClient()) {
        final Map<String, Object> bindings = new HashMap<>();
        bindings.put(null, "123");
        final RequestMessage request = RequestMessage.build(Tokens.OPS_EVAL)
                .addArg(Tokens.ARGS_GREMLIN, "[1,2,3,4,5,6,7,8,9,0]").addArg(Tokens.ARGS_BINDINGS, bindings)
                .create();/*from   www.ja  va2 s . c  o  m*/
        final CountDownLatch latch = new CountDownLatch(1);
        final AtomicBoolean pass = new AtomicBoolean(false);
        client.submit(request, result -> {
            if (result.getStatus().getCode() != ResponseStatusCode.PARTIAL_CONTENT) {
                pass.set(ResponseStatusCode.REQUEST_ERROR_INVALID_REQUEST_ARGUMENTS == result.getStatus()
                        .getCode());
                latch.countDown();
            }
        });

        if (!latch.await(3000, TimeUnit.MILLISECONDS))
            fail("Request should have returned error, but instead timed out");
        assertTrue(pass.get());
    }
}

From source file:org.apache.hadoop.yarn.server.resourcemanager.recovery.TestFSRMStateStore.java

@Test(timeout = 30000)
public void testFSRMStateStoreClientRetry() throws Exception {
    HdfsConfiguration conf = new HdfsConfiguration();
    MiniDFSCluster cluster = new MiniDFSCluster.Builder(conf).numDataNodes(2).build();
    cluster.waitActive();//from www.  jav  a  2 s.c  om
    try {
        TestFSRMStateStoreTester fsTester = new TestFSRMStateStoreTester(cluster, false);
        final RMStateStore store = fsTester.getRMStateStore();
        store.setRMDispatcher(new TestDispatcher());
        final AtomicBoolean assertionFailedInThread = new AtomicBoolean(false);
        cluster.shutdownNameNodes();

        Thread clientThread = new Thread() {
            @Override
            public void run() {
                try {
                    store.storeApplicationStateInternal(ApplicationId.newInstance(100L, 1),
                            ApplicationStateData.newInstance(111, 111, "user", null, RMAppState.ACCEPTED,
                                    "diagnostics", 333, null));
                } catch (Exception e) {
                    assertionFailedInThread.set(true);
                    e.printStackTrace();
                }
            }
        };
        Thread.sleep(2000);
        clientThread.start();
        cluster.restartNameNode();
        clientThread.join();
        Assert.assertFalse(assertionFailedInThread.get());
    } finally {
        cluster.shutdown();
    }
}

From source file:org.apache.tinkerpop.gremlin.groovy.engine.GremlinExecutorTest.java

@Test
public void shouldInterruptWhile() throws Exception {
    final Map<String, List<Object>> compilerCustomizerConfig = new HashMap<>();
    compilerCustomizerConfig.put(ThreadInterruptCustomizerProvider.class.getName(), new ArrayList<>());

    final Map<String, Object> config = new HashMap<>();
    config.put("compilerCustomizerProviders", compilerCustomizerConfig);

    final GremlinExecutor gremlinExecutor = GremlinExecutor.build()
            .addEngineSettings("gremlin-groovy", Collections.emptyList(), Collections.emptyList(),
                    Arrays.asList(PATHS.get("GremlinExecutorInit.groovy")), config)
            .create();/*from ww w. j  a v a 2  s .  c  o  m*/
    final AtomicBoolean asserted = new AtomicBoolean(false);

    final Thread t = new Thread(() -> {
        try {
            gremlinExecutor
                    .eval("s = System.currentTimeMillis();\nwhile((System.currentTimeMillis() - s) < 10000) {}")
                    .get();
        } catch (Exception se) {
            asserted.set(se instanceof InterruptedException);
        }
    });

    t.start();
    Thread.sleep(100);
    t.interrupt();
    while (t.isAlive()) {
    }

    assertTrue(asserted.get());
}

From source file:org.springsource.ide.eclipse.commons.internal.configurator.ConfiguratorImporter.java

public List<ConfigurableExtension> detectExtensions(final IProgressMonitor monitor) {
    final List<ConfigurableExtension> result = new ArrayList<ConfigurableExtension>();
    Set<WorkspaceConfiguratorParticipant> participants = ParticipantExtensionPointReader.getParticipants();
    for (final WorkspaceConfiguratorParticipant participant : participants) {
        SafeRunner.run(new ISafeRunnable() {
            public void handleException(Throwable exception) {
                // logged by super class
            }/*from w  ww. j a va 2  s. com*/

            public void run() throws Exception {
                List<ConfigurableExtension> extensions = participant.detectExtensions(ConfiguratorImporter.this,
                        monitor);
                result.addAll(extensions);
            }
        });
    }
    Set<InstallableItem> installableItems = ParticipantExtensionPointReader.getInstallableItems();
    for (final InstallableItem item : installableItems) {
        boolean found = false;
        for (ConfigurableExtension extension : result) {
            if (extension.getId().equals(item.getId())) {
                extension.setInstallableItem(item);
                found = true;
            }
        }
        if (!found) {
            for (final WorkspaceConfiguratorParticipant participant : participants) {
                if (participant.getId().equals(item.getConfiguratorId())) {
                    final AtomicBoolean added = new AtomicBoolean(false);
                    SafeRunner.run(new ISafeRunnable() {
                        public void handleException(Throwable exception) {
                            // logged by super class
                        }

                        public void run() throws Exception {
                            ConfigurableExtension extension = participant.createExtension(item, monitor);
                            if (extension != null) {
                                result.add(extension);
                                added.set(true);
                            }
                        }
                    });
                    if (added.get()) {
                        break;
                    }
                }
            }
        }
    }

    return result;
}

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

@Test
public void should_insert_if_not_exists() throws Exception {
    //Given/* www.  j a va 2s  .  co  m*/
    final long id = 100L;
    final Date date = buildDateKey();
    scriptExecutor.executeScriptTemplate("SimpleEntity/insert_single_row.cql",
            ImmutableMap.of("id", id, "table", "simple"));

    final SimpleEntity entity = new SimpleEntity(id, date, "value");
    final AtomicBoolean error = new AtomicBoolean(false);
    final AtomicLong currentId = new AtomicLong(0L);

    final LWTResultListener lwtListener = new LWTResultListener() {

        @Override
        public void onSuccess() {

        }

        @Override
        public void onError(LWTResult lwtResult) {
            error.getAndSet(true);
            currentId.getAndSet(lwtResult.currentValues().getTyped("id"));
        }
    };

    //When
    manager.crud().insert(entity).ifNotExists().withLwtResultListener(lwtListener).execute();

    //Then
    assertThat(error.get()).isTrue();
    assertThat(currentId.get()).isEqualTo(id);
}

From source file:li.strolch.runtime.main.MainStarter.java

public int keepAlive() {

    final AtomicBoolean atomicBoolean = new AtomicBoolean();

    Runtime.getRuntime().addShutdownHook(new Thread() {
        @Override/*from   w  ww  .  j  ava2s  . c  o m*/
        public void run() {
            synchronized (MainStarter.class) {
                System.out.println("VM Shutting down. Stopping Strolch...");
                System.out.println("");
                System.out.println("Strolch application " + MainStarter.this.getAgent().getApplicationName()
                        + " shutting down...");
                MainStarter.this.getAgent().stop();
                MainStarter.this.getAgent().destroy();
                System.out.println("Strolch application " + MainStarter.this.getAgent().getApplicationName()
                        + " shut down. Exiting VM.");

                atomicBoolean.set(true);
                MainStarter.class.notify();
            }
        }
    });

    logger.info("");
    logger.info("Strolch application " + getAgent().getApplicationName() + " started ");
    while (!atomicBoolean.get()) {
        synchronized (MainStarter.class) {
            try {
                MainStarter.class.wait();
            } catch (InterruptedException e) {
                logger.error("Interrupted.");
                return 1;
            }
        }
    }

    return 0;
}

From source file:io.druid.segment.realtime.plumber.RealtimePlumberSchoolTest.java

private void testPersist(final Object commitMetadata) throws Exception {
    final AtomicBoolean committed = new AtomicBoolean(false);
    plumber.getSinks().put(0L, new Sink(new Interval(0, TimeUnit.HOURS.toMillis(1)), schema, tuningConfig,
            new DateTime("2014-12-01T12:34:56.789").toString()));
    Assert.assertNull(plumber.startJob());

    final InputRow row = EasyMock.createNiceMock(InputRow.class);
    EasyMock.expect(row.getTimestampFromEpoch()).andReturn(0L);
    EasyMock.expect(row.getDimensions()).andReturn(new ArrayList<String>());
    EasyMock.replay(row);//from  ww  w.j  a  v a2 s. c  om
    final Committer committer = new Committer() {
        @Override
        public Object getMetadata() {
            return commitMetadata;
        }

        @Override
        public void run() {
            committed.set(true);
        }
    };
    plumber.add(row, Suppliers.ofInstance(committer));
    plumber.persist(committer);

    while (!committed.get()) {
        Thread.sleep(100);
    }
    plumber.getSinks().clear();
    plumber.finishJob();
}