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.hadoop.hbase.ipc.TestAsyncIPC.java

@Test
public void testRTEDuringAsyncConnectionSetup() throws Exception {
    TestRpcServer rpcServer = new TestRpcServer();
    AsyncRpcClient client = createRpcClientRTEDuringConnectionSetup(CONF);
    try {/*from ww  w.  jav a2s  .c  om*/
        rpcServer.start();
        InetSocketAddress address = rpcServer.getListenerAddress();
        MethodDescriptor md = SERVICE.getDescriptorForType().findMethodByName("echo");
        EchoRequestProto param = EchoRequestProto.newBuilder().setMessage("hello").build();

        RpcChannel channel = client.createRpcChannel(
                ServerName.valueOf(address.getHostName(), address.getPort(), System.currentTimeMillis()),
                User.getCurrent(), 0);

        final AtomicBoolean done = new AtomicBoolean(false);

        PayloadCarryingRpcController controller = new PayloadCarryingRpcController();
        controller.notifyOnFail(new RpcCallback<IOException>() {
            @Override
            public void run(IOException e) {
                done.set(true);
                LOG.info("Caught expected exception: " + e.toString());
                assertTrue(StringUtils.stringifyException(e).contains("Injected fault"));
            }
        });

        channel.callMethod(md, controller, param, md.getOutputType().toProto(), new RpcCallback<Message>() {
            @Override
            public void run(Message parameter) {
                done.set(true);
                fail("Expected an exception to have been thrown!");
            }
        });

        TEST_UTIL.waitFor(1000, new Waiter.Predicate<Exception>() {
            @Override
            public boolean evaluate() throws Exception {
                return done.get();
            }
        });
    } finally {
        client.close();
        rpcServer.stop();
    }
}

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

@Test
public void should_delete_if_exists() throws Exception {
    //Given/*  w  ww  . jav a  2  s  . c o m*/
    final long id = RandomUtils.nextLong(0L, Long.MAX_VALUE);
    final Date date = buildDateKey();

    final AtomicBoolean error = new AtomicBoolean(false);
    final AtomicBoolean applied = new AtomicBoolean(true);

    final LWTResultListener lwtListener = new LWTResultListener() {

        @Override
        public void onSuccess() {

        }

        @Override
        public void onError(LWTResult lwtResult) {
            error.getAndSet(true);
            applied.getAndSet(lwtResult.currentValues().getTyped("[applied]"));
        }
    };

    //When
    manager.crud().deleteById(id, date).ifExists().withLwtResultListener(lwtListener).execute();

    //Then
    assertThat(error.get()).isTrue();
    assertThat(applied.get()).isFalse();
}

From source file:info.archinnov.achilles.test.integration.tests.LWTOperationsIT.java

@Test
public void should_insert_and_notify_LWT_listener_on_success() throws Exception {
    final AtomicBoolean LWTSuccess = new AtomicBoolean(false);
    LWTResultListener listener = new LWTResultListener() {
        @Override/*from w w w  .  j ava  2s  . c om*/
        public void onSuccess() {
            LWTSuccess.compareAndSet(false, true);
        }

        @Override
        public void onError(LWTResult lwtResult) {

        }
    };

    //Given
    final EntityWithEnum entityWithEnum = new EntityWithEnum(10L, "name", EACH_QUORUM);

    //When
    manager.insertOrUpdate(entityWithEnum, OptionsBuilder.ifNotExists().lwtResultListener(listener));
    final EntityWithEnum found = manager.find(EntityWithEnum.class, 10L);

    //Then
    assertThat(found).isNotNull();
    assertThat(found.getName()).isEqualTo("name");
    assertThat(found.getConsistencyLevel()).isEqualTo(EACH_QUORUM);
    assertThat(LWTSuccess.get()).isTrue();
}

From source file:com.vmware.admiral.request.ContainerControlLoopServiceTest.java

@SuppressWarnings("unchecked")
@Test//from   www  .  j a va 2s . c  om
public void redeploymentOfSingleContainers() throws Throwable {
    containerDescription2 = createContainerDescription(false);

    // provision 3 single containers, 2 of them in ERROR state
    ContainerState state = null;
    for (int i = 0; i < SINGLE_CONTAINERS_TO_BE_PROVISIONED; i++) {
        state = provisionContainer(containerDescription2.documentSelfLink);

        if (i < SINGLE_CONTAINERS_TO_BE_PROVISIONED - 1) {
            state.powerState = PowerState.ERROR;
            doPut(state);
        }
    }

    Map<String, List<String>> containersPerContextId = new HashMap<>();

    retrieveContainerStates(containerDescription2.documentSelfLink).thenAccept(containerStates -> {
        containerStates.stream().forEach(cs -> {
            containersPerContextId.put(cs.customProperties.get(RequestUtils.FIELD_NAME_CONTEXT_ID_KEY),
                    Arrays.asList(cs.documentSelfLink));
        });
    });

    doOperation(new ContainerControlLoopState(),
            UriUtils.buildUri(host, ContainerControlLoopService.CONTROL_LOOP_INFO_LINK), false,
            Service.Action.PATCH);

    Map<String, List<String>> redeployedContainersPerContextId = new HashMap<>();
    AtomicBoolean containerFromDesc2Redeployed = new AtomicBoolean(false);

    waitFor(() -> {
        // get all containers from containerDescription2
        retrieveContainerStates(containerDescription2.documentSelfLink).thenAccept(containerStates -> {
            long healthyContainers = containerStates.stream()
                    .filter(cs -> PowerState.RUNNING.equals(cs.powerState)).count();
            host.log("Healthy containers from %s : %d", containerDescription2.documentSelfLink,
                    healthyContainers);
            containerFromDesc2Redeployed.set(SINGLE_CONTAINERS_TO_BE_PROVISIONED == healthyContainers
                    && SINGLE_CONTAINERS_TO_BE_PROVISIONED == containerStates.size());

            containerStates.stream().forEach(cs -> {
                redeployedContainersPerContextId.put(
                        cs.customProperties.get(RequestUtils.FIELD_NAME_CONTEXT_ID_KEY),
                        Arrays.asList(cs.documentSelfLink));
            });
        });

        if (containerFromDesc2Redeployed.get()) {
            containersPerContextId.entrySet().stream().forEach(m -> {
                String contextId = m.getKey();
                List<String> redeployedContainers = redeployedContainersPerContextId.get(contextId);
                host.log("Redeployed container: %s -> %s", StringUtils.join(m.getValue()),
                        StringUtils.join(redeployedContainers));
            });
        }

        return containerFromDesc2Redeployed.get();
    });
}

From source file:com.google.dart.engine.services.internal.refactoring.ExtractMethodRefactoringImpl.java

/**
 * @return <code>true</code> if the given {@link VariableElement} is referenced after the
 *         {@link #selectionRange}.//from   w  w  w  . j av a  2 s.  co  m
 */
private boolean isUsedAfterSelection(final VariableElement element) {
    final AtomicBoolean result = new AtomicBoolean();
    parentMember.accept(new GeneralizingASTVisitor<Void>() {
        @Override
        public Void visitSimpleIdentifier(SimpleIdentifier node) {
            VariableElement nodeElement = CorrectionUtils.getLocalVariableElement(node);
            if (nodeElement == element) {
                int nodeOffset = node.getOffset();
                if (nodeOffset > selectionRange.getEnd()) {
                    result.set(true);
                }
            }
            return null;
        }
    });
    return result.get();
}

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

@Test
public void shouldCallSuccess() throws Exception {
    final AtomicBoolean timeoutCalled = new AtomicBoolean(false);
    final AtomicBoolean successCalled = new AtomicBoolean(false);
    final AtomicBoolean failureCalled = new AtomicBoolean(false);
    final GremlinExecutor gremlinExecutor = GremlinExecutor.build()
            .afterFailure((b, e) -> failureCalled.set(true)).afterSuccess((b) -> successCalled.set(true))
            .afterTimeout((b) -> timeoutCalled.set(true)).create();
    assertEquals(2, gremlinExecutor.eval("1+1").get());

    // need to wait long enough for the callback to register
    Thread.sleep(500);/*from ww  w.  ja  va  2 s .c om*/

    assertFalse(timeoutCalled.get());
    assertTrue(successCalled.get());
    assertFalse(failureCalled.get());
    gremlinExecutor.close();
}

From source file:org.apache.hadoop.hbase.client.TestAsyncProcess.java

@Test
public void testSubmitTrue() throws IOException {
    final AsyncProcess ap = new MyAsyncProcess(createHConnection(), conf, false);
    ap.tasksInProgress.incrementAndGet();
    final AtomicInteger ai = new AtomicInteger(1);
    ap.taskCounterPerRegion.put(hri1.getRegionName(), ai);

    final AtomicBoolean checkPoint = new AtomicBoolean(false);
    final AtomicBoolean checkPoint2 = new AtomicBoolean(false);

    Thread t = new Thread() {
        @Override//  w  w w .j  ava 2  s . co m
        public void run() {
            Threads.sleep(1000);
            Assert.assertFalse(checkPoint.get()); // TODO: this is timing-dependent
            ai.decrementAndGet();
            ap.tasksInProgress.decrementAndGet();
            checkPoint2.set(true);
        }
    };

    List<Put> puts = new ArrayList<Put>();
    Put p = createPut(1, true);
    puts.add(p);

    ap.submit(DUMMY_TABLE, puts, false, null, false);
    Assert.assertFalse(puts.isEmpty());

    t.start();

    ap.submit(DUMMY_TABLE, puts, true, null, false);
    Assert.assertTrue(puts.isEmpty());

    checkPoint.set(true);
    while (!checkPoint2.get()) {
        Threads.sleep(1);
    }
}

From source file:io.nats.client.ITClusterTest.java

@Test
public void testProperReconnectDelay() throws Exception {
    try (NatsServer s1 = runServerOnPort(1222)) {
        Options opts = new Options.Builder(defaultOptions()).dontRandomize().build();
        opts.servers = Nats.processUrlArray(testServers);

        final CountDownLatch latch = new CountDownLatch(1);
        opts.disconnectedCb = new DisconnectedCallback() {
            public void onDisconnect(ConnectionEvent event) {
                event.getConnection().setDisconnectedCallback(null);
                latch.countDown();//ww w.  ja  v a2s .c o  m
            }
        };

        final AtomicBoolean ccbCalled = new AtomicBoolean(false);
        opts.closedCb = new ClosedCallback() {
            public void onClose(ConnectionEvent event) {
                ccbCalled.set(true);
            }
        };

        try (Connection c = opts.connect()) {
            assertFalse(c.isClosed());

            s1.shutdown();
            // wait for disconnect
            assertTrue("Did not receive a disconnect callback message", await(latch, 2, TimeUnit.SECONDS));

            // Wait, want to make sure we don't spin on reconnect to non-existent servers.
            sleep(1, TimeUnit.SECONDS);

            assertFalse("Closed CB was triggered, should not have been.", ccbCalled.get());
            assertEquals("Wrong state: " + c.getState(), c.getState(), RECONNECTING);
        }
    }
}

From source file:com.netflix.curator.TestSessionFailRetryLoop.java

@Test
public void testRetry() throws Exception {
    Timing timing = new Timing();
    final CuratorZookeeperClient client = new CuratorZookeeperClient(server.getConnectString(),
            timing.session(), timing.connection(), null, new RetryOneTime(1));
    SessionFailRetryLoop retryLoop = client.newSessionFailRetryLoop(SessionFailRetryLoop.Mode.RETRY);
    retryLoop.start();//from   w  w  w .  j a v  a 2  s  . co  m
    try {
        client.start();
        final AtomicBoolean secondWasDone = new AtomicBoolean(false);
        final AtomicBoolean firstTime = new AtomicBoolean(true);
        while (retryLoop.shouldContinue()) {
            try {
                RetryLoop.callWithRetry(client, new Callable<Void>() {
                    @Override
                    public Void call() throws Exception {
                        if (firstTime.compareAndSet(true, false)) {
                            Assert.assertNull(client.getZooKeeper().exists("/foo/bar", false));
                            KillSession.kill(client.getZooKeeper(), server.getConnectString());
                            client.getZooKeeper();
                            client.blockUntilConnectedOrTimedOut();
                        }

                        Assert.assertNull(client.getZooKeeper().exists("/foo/bar", false));
                        return null;
                    }
                });

                RetryLoop.callWithRetry(client, new Callable<Void>() {
                    @Override
                    public Void call() throws Exception {
                        Assert.assertFalse(firstTime.get());
                        Assert.assertNull(client.getZooKeeper().exists("/foo/bar", false));
                        secondWasDone.set(true);
                        return null;
                    }
                });
            } catch (Exception e) {
                retryLoop.takeException(e);
            }
        }

        Assert.assertTrue(secondWasDone.get());
    } finally {
        retryLoop.close();
        IOUtils.closeQuietly(client);
    }
}

From source file:com.spectralogic.ds3client.integration.DataIntegrity_Test.java

@Test
public void callerSuppliedChecksum() throws IOException, SignatureException, XmlProcessingException {
    final String bucketName = "caller_supplied_checksum_test";

    try {//ww  w.  j a v  a2 s.c  om
        HELPERS.ensureBucketExists(bucketName, envDataPolicyId);

        final List<Ds3Object> objs = Lists.newArrayList(new Ds3Object("beowulf.txt", 294059));
        final Ds3ClientHelpers.Job job = HELPERS.startWriteJob(bucketName, objs,
                WriteJobOptions.create().withChecksumType(ChecksumType.Type.MD5));

        final AtomicBoolean callbackCalled = new AtomicBoolean(false);

        job.withChecksum(new ChecksumFunction() {
            @Override
            public String compute(final BulkObject obj, final ByteChannel channel) {
                if (obj.getName().equals("beowulf.txt")) {
                    callbackCalled.set(true);
                    return "rCu751L6xhB5zyL+soa3fg==";
                }
                return null;
            }
        });

        final SingleChecksumListener listener = new SingleChecksumListener();

        job.attachChecksumListener(listener);

        job.transfer(new ResourceObjectPutter("books/"));

        final String checksum = listener.getChecksum();

        assertThat(checksum, is(notNullValue()));
        assertThat(checksum, is("rCu751L6xhB5zyL+soa3fg=="));
        assertTrue(callbackCalled.get());

    } finally {
        Util.deleteAllContents(client, bucketName);
    }
}