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

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

Introduction

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

Prototype

public final boolean compareAndSet(boolean expectedValue, boolean newValue) 

Source Link

Document

Atomically sets the value to newValue if the current value == expectedValue , with memory effects as specified by VarHandle#compareAndSet .

Usage

From source file:Main.java

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

    atomicBoolean.compareAndSet(true, true);

    System.out.println(atomicBoolean);
}

From source file:org.springframework.http.server.reactive.ServletHttpHandlerAdapter.java

/**
 * We cannot combine ERROR_LISTENER and HandlerResultSubscriber due to:
 * https://issues.jboss.org/browse/WFLY-8515
 *//* w  ww . j  av  a  2  s  . co  m*/
private static void runIfAsyncNotComplete(AsyncContext asyncContext, AtomicBoolean isCompleted, Runnable task) {
    try {
        if (asyncContext.getRequest().isAsyncStarted() && isCompleted.compareAndSet(false, true)) {
            task.run();
        }
    } catch (IllegalStateException ex) {
        // Ignore: AsyncContext recycled and should not be used
        // e.g. TIMEOUT_LISTENER (above) may have completed the AsyncContext
    }
}

From source file:com.joyent.manta.http.ApacheHttpGetResponseEntityContentContinuatorTest.java

private static HttpClient prepareMockedClient(final int responseCode, final String etag,
        final HttpRange.Response contentRange, final Long contentLength, final HttpEntity entity)
        throws IOException {
    final HttpClient client = mock(HttpClient.class);
    final AtomicBoolean responded = new AtomicBoolean(false);

    when(client.execute(any(HttpUriRequest.class), any(HttpContext.class))).then(invocation -> {
        if (!responded.compareAndSet(false, true)) {
            throw new IllegalStateException("this mocked client only provides a single response");
        }//from  w w w  .j  av a2s.c  o m

        final HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, responseCode, "mocked");

        if (etag != null) {
            response.setHeader(ETAG, etag);
        }

        if (contentRange != null) {
            response.setHeader(CONTENT_RANGE, contentRange.render());
        }

        if (contentLength != null) {
            response.setHeader(CONTENT_LENGTH, contentLength.toString());
        }

        if (entity != null) {
            response.setEntity(entity);
        }

        return response;
    });

    return client;
}

From source file:ubicrypt.core.provider.file.FileProviderTest.java

private void crud(final int size) throws Exception {
    final byte[] bytes = new byte[size];
    new Random().nextBytes(bytes);

    final AtomicBoolean b = new AtomicBoolean(false);
    final AtomicReference<String> fname = new AtomicReference<>();
    fp.post(new ByteArrayInputStream(bytes)).toBlocking().forEach(name -> {
        fname.set(name);/*  www . j  a v  a 2 s .co  m*/
        assertThat(b.compareAndSet(false, true)).isTrue();
        assertThat(name).isNotNull();
    });

    assertThat(IOUtils.toByteArray(fp.get(fname.get()).toBlocking().first())).isEqualTo(bytes);

    new Random().nextBytes(bytes);
    fp.put(fname.get(), new ByteArrayInputStream(bytes)).toBlocking().last();

    assertThat(IOUtils.toByteArray(fp.get(fname.get()).toBlocking().first())).isEqualTo(bytes);

    fp.delete(fname.get()).toBlocking().firstOrDefault(null);

    assertThatThrownBy(() -> fp.get(fname.get()).toBlocking().first());
}

From source file:org.wso2.carbon.core.deployment.CarbonDeploymentSchedulerTask.java

/**
 * This method checks and returns whether the repo.update.required parameter is set or
 * whether we need to do the mandatory repository sync in the current iteration of this
 * periodic task.// ww w  .  jav a2s.c om
 *
 * The repo.update.required parameter is accessed and set in SynchronizeRepositoryRequest class.
 *
 * Mandatory repo sync is calculated by using a flag that is decreasing in each iteration. When it
 * reaches zero, it's time to do the update
 *
 * @return true if an update is required, false otherwise.
 */
private boolean isRepoUpdateRequired() {
    boolean updateRequired;

    AtomicBoolean value = (AtomicBoolean) axisConfig.getParameter(REPO_UPDATE_REQUIRED).getValue();
    updateRequired = value.compareAndSet(true, false);

    if (iterationsForNextRepoUpdate-- <= 0) {
        updateRequired = true;
        //Randomize the next repo update iteration time
        iterationsForNextRepoUpdate = getIterationsNoForNextRepoUpdate();
        if (log.isDebugEnabled()) {
            log.debug("Triggering the mandatory artifact synchronization. " + "Next sync is in "
                    + iterationsForNextRepoUpdate + " iterations. " + "tenant : " + tenantDomain);
        }
    }

    return updateRequired;
}

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

private void updateCurrentlyServingReplica(ScannerCallable scanner, Result[] result, AtomicBoolean done,
        ExecutorService pool) {/*from www .j  a v a 2s . c om*/
    if (done.compareAndSet(false, true)) {
        if (currentScannerCallable != scanner)
            replicaSwitched.set(true);
        currentScannerCallable = scanner;
        // store where to start the replica scanner from if we need to.
        if (result != null && result.length != 0)
            this.lastResult = result[result.length - 1];
        if (LOG.isTraceEnabled()) {
            LOG.trace("Setting current scanner as id=" + currentScannerCallable.scannerId
                    + " associated with replica=" + currentScannerCallable.getHRegionInfo().getReplicaId());
        }
        // close all outstanding replica scanners but the one we heard back from
        outstandingCallables.remove(scanner);
        for (ScannerCallable s : outstandingCallables) {
            if (LOG.isTraceEnabled()) {
                LOG.trace("Closing scanner id=" + s.scannerId + ", replica=" + s.getHRegionInfo().getRegionId()
                        + " because slow and replica="
                        + this.currentScannerCallable.getHRegionInfo().getReplicaId() + " succeeded");
            }
            // Submit the "close" to the pool since this might take time, and we don't
            // want to wait for the "close" to happen yet. The "wait" will happen when
            // the table is closed (when the awaitTermination of the underlying pool is called)
            s.setClose();
            final RetryingRPC r = new RetryingRPC(s);
            pool.submit(new Callable<Void>() {
                @Override
                public Void call() throws Exception {
                    r.call(scannerTimeout);
                    return null;
                }
            });
        }
        // now clear outstandingCallables since we scheduled a close for all the contained scanners
        outstandingCallables.clear();
    }
}

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 ww . j  a va2s.  com*/
    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: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   ww w  .  j  av a 2 s .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:org.zenoss.zep.index.impl.EventIndexerImpl.java

private int doIndex(long throughTime) throws ZepException {
    final EventPostIndexContext context = new EventPostIndexContext() {
        @Override//  w  w  w.j av  a2  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.netflix.curator.TestSessionFailRetryLoop.java

@Test
public void testRetryStatic() 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  av  a 2  s .c  o m
    try {
        client.start();
        final AtomicBoolean secondWasDone = new AtomicBoolean(false);
        final AtomicBoolean firstTime = new AtomicBoolean(true);
        SessionFailRetryLoop.callWithRetry(client, SessionFailRetryLoop.Mode.RETRY, new Callable<Object>() {
            @Override
            public Object call() throws Exception {
                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;
                    }
                });
                return null;
            }
        });

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