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

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

Introduction

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

Prototype

public AtomicBoolean(boolean initialValue) 

Source Link

Document

Creates a new AtomicBoolean with the given initial value.

Usage

From source file:com.dgtlrepublic.anitomyj.Token.java

/**
 * Validates a token against the {@code flags}. The {@code flags} is used as a search parameter.
 *
 * @param token the token/* w w w . j ava 2 s . com*/
 * @param flags the flags the token must conform against
 * @return true if the token conforms to the set of {@code flags}; false otherwise
 */
public static boolean checkTokenFlags(Token token, EnumSet<TokenFlag> flags) {
    /** simple alias to check if flag is a part of the set */
    Function<TokenFlag, Boolean> checkFlag = flags::contains;

    /** make sure token is the correct closure */
    if (CollectionUtils.containsAny(flags, kFlagMaskEnclosed)) {
        boolean success = checkFlag.apply(kFlagEnclosed) == token.enclosed;
        if (!success)
            return false; /** not enclosed correctly (e.g enclosed when we're looking for non-enclosed) */
    }

    /** make sure token is the correct category */
    if (CollectionUtils.containsAny(flags, kFlagMaskCategories)) {
        AtomicBoolean success = new AtomicBoolean(false);
        TriConsumer<TokenFlag, TokenFlag, TokenCategory> checkCategory = (fe, fn, c) -> {
            if (!success.get()) {
                boolean result = checkFlag.apply(fe) ? token.category == c
                        : checkFlag.apply(fn) && token.category != c;
                success.set(result);
            }
        };

        checkCategory.accept(kFlagBracket, kFlagNotBracket, kBracket);
        checkCategory.accept(kFlagDelimiter, kFlagNotDelimiter, kDelimiter);
        checkCategory.accept(kFlagIdentifier, kFlagNotIdentifier, kIdentifier);
        checkCategory.accept(kFlagUnknown, kFlagNotUnknown, kUnknown);
        checkCategory.accept(kFlagNotValid, kFlagValid, kInvalid);
        if (!success.get())
            return false;
    }

    return true;
}

From source file:com.streamsets.pipeline.stage.origin.mongodb.oplog.MongoDBOplogSourceIT.java

@Before
public void createCollection() throws Exception {
    MongoDatabase db = mongoClient.getDatabase(DATABASE);
    testCollectionName = name.getMethodName();
    db.createCollection(testCollectionName);
    final long currentTime = System.currentTimeMillis();
    //To make sure that oplog is read on each method after we created the above collection.
    //We let this current second pass, before we get the initial timestamp seconds.
    Awaitility.await().untilTrue(new AtomicBoolean((System.currentTimeMillis() - currentTime) > 1000));
    //So we can skip old oplogs and just start with whatever this test is producing
    initialTs = getInitialTsFromCurrentTime();
    testDocuments = mongoClient.getDatabase(DATABASE).getCollection(testCollectionName);
    mongoCursorFindIterable = mongoClient.getDatabase("local").getCollection(OPLOG_COLLECTION).find()
            //As the collection is a capped collection we use Tailable cursor which will return results in natural order in this case
            //based on ts timestamp field.
            //Tailable Await does not return and blocks, so we are using tailable.
            .cursorType(CursorType.Tailable);
}

From source file:com.netflix.dyno.connectionpool.impl.lb.CircularListTest.java

@Test
public void testSingleThreadWithElementRemove() throws Exception {

    final AtomicBoolean stop = new AtomicBoolean(false);

    Future<Map<Integer, Integer>> future = threadPool.submit(new Callable<Map<Integer, Integer>>() {

        @Override/* ww w  .  ja v  a 2s .c  o  m*/
        public Map<Integer, Integer> call() throws Exception {

            TestWorker worker = new TestWorker();

            while (!stop.get()) {
                worker.process();
            }

            return worker.map;
        }
    });

    Thread.sleep(200);

    List<Integer> newList = new ArrayList<Integer>();
    newList.addAll(iList);

    final List<Integer> removedElements = new ArrayList<Integer>();
    removedElements.add(newList.remove(2));
    removedElements.add(newList.remove(5));
    removedElements.add(newList.remove(6));

    cList.swapWithList(newList);

    Thread.sleep(200);
    stop.set(true);

    Map<Integer, Integer> result = future.get();

    Map<Integer, Integer> subMap = CollectionUtils.filterKeys(result, new Predicate<Integer>() {
        @Override
        public boolean apply(Integer input) {
            return !removedElements.contains(input);
        }
    });

    checkValues(new ArrayList<Integer>(subMap.values()));
}

From source file:io.dropwizard.discovery.bundle.ServiceDiscoveryBundleRotationTest.java

@Before
public void setup() throws Exception {

    when(jerseyEnvironment.getResourceConfig()).thenReturn(new DropwizardResourceConfig());
    when(environment.jersey()).thenReturn(jerseyEnvironment);
    when(environment.lifecycle()).thenReturn(lifecycleEnvironment);
    when(environment.healthChecks()).thenReturn(healthChecks);
    when(environment.getObjectMapper()).thenReturn(new ObjectMapper());
    AdminEnvironment adminEnvironment = mock(AdminEnvironment.class);
    doNothing().when(adminEnvironment).addTask(any());
    when(environment.admin()).thenReturn(adminEnvironment);

    testingCluster.start();/*from   w  w  w.  j  ava2 s.c om*/

    serviceDiscoveryConfiguration = ServiceDiscoveryConfiguration.builder()
            .zookeeper(testingCluster.getConnectString()).namespace("test").environment("testing")
            .connectionRetryIntervalMillis(5000).publishedHost("TestHost").publishedPort(8021)
            .initialRotationStatus(true).build();
    bundle.initialize(bootstrap);

    bundle.run(configuration, environment);
    rotationStatus = bundle.getRotationStatus();

    final AtomicBoolean started = new AtomicBoolean(false);
    executorService.submit(() -> lifecycleEnvironment.getManagedObjects().forEach(object -> {
        try {
            object.start();
            started.set(true);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }));
    while (!started.get()) {
        Thread.sleep(1000);
        log.debug("Waiting for framework to start...");
    }

}

From source file:com.navercorp.pinpoint.profiler.sender.UdpDataSenderTest.java

private boolean sendMessage_getLimit(TBase tbase, long waitTimeMillis) throws InterruptedException {
    final AtomicBoolean limitCounter = new AtomicBoolean(false);
    final CountDownLatch latch = new CountDownLatch(1);
    final MessageConverter<TBase<?, ?>> messageConverter = new BypassMessageConverter<TBase<?, ?>>();
    final MessageSerializer<ByteMessage> thriftMessageSerializer = new ThriftUdpMessageSerializer(
            messageConverter, ThriftUdpMessageSerializer.UDP_MAX_PACKET_LENGTH) {
        @Override/*  w w w  .j  a va2 s . c o  m*/
        protected boolean isLimit(int interBufferSize) {
            final boolean limit = super.isLimit(interBufferSize);
            limitCounter.set(limit);
            latch.countDown();
            return limit;
        }
    };

    UdpDataSender sender = new UdpDataSender("localhost", PORT, "test", 128, 1000, 1024 * 64 * 100,
            thriftMessageSerializer);
    try {
        sender.send(tbase);
        latch.await(waitTimeMillis, TimeUnit.MILLISECONDS);
    } finally {
        sender.stop();
    }
    return limitCounter.get();
}

From source file:com.jayway.restassured.path.xml.XmlPathObjectDeserializationTest.java

@Test
public void xml_path_supports_custom_deserializer() {
    // Given/*from   www  . ja  v a2s.  com*/
    final AtomicBoolean customDeserializerUsed = new AtomicBoolean(false);

    final XmlPath xmlPath = new XmlPath(COOL_GREETING)
            .using(xmlPathConfig().defaultObjectDeserializer(new XmlPathObjectDeserializer() {
                public <T> T deserialize(ObjectDeserializationContext ctx) {
                    customDeserializerUsed.set(true);
                    final String xml = ctx.getDataToDeserialize().asString();
                    final Greeting greeting = new Greeting();
                    greeting.setFirstName(StringUtils.substringBetween(xml, "<firstName>", "</firstName>"));
                    greeting.setLastName(StringUtils.substringBetween(xml, "<lastName>", "</lastName>"));
                    return (T) greeting;
                }
            }));

    // When
    final Greeting greeting = xmlPath.getObject("", Greeting.class);

    // Then
    assertThat(greeting.getFirstName(), equalTo("John"));
    assertThat(greeting.getLastName(), equalTo("Doe"));
    assertThat(customDeserializerUsed.get(), is(true));
}

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

@SuppressWarnings("unchecked")
@Test/*from   w w w .j  a v a  2  s  .  com*/
public void testRedeploymentOfAContainerInCluster() throws Throwable {

    containerDescription1 = createContainerDescription(false);
    containerDescription1._cluster = 2;
    doPut(containerDescription1);

    // provision 2 containers in cluster
    ContainerState state = provisionContainer(containerDescription1.documentSelfLink);
    // change the power state of one of them
    state.powerState = PowerState.ERROR;
    doPut(state);

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

    retrieveContainerStates(containerDescription1.documentSelfLink).thenAccept(containerStates -> {
        List<String> containersFromDesc1 = containerStates.stream().map(cs -> cs.documentSelfLink)
                .collect(Collectors.toList());
        assertEquals(2, containersFromDesc1.size());

        // clustered containers have same context_id
        containersPerContextId.put(
                containerStates.get(0).customProperties.get(RequestUtils.FIELD_NAME_CONTEXT_ID_KEY),
                containersFromDesc1);
    });

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

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

    AtomicBoolean containerFromDesc1Redeployed = new AtomicBoolean(false);

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

            List<String> containersFromDesc1 = containerStates.stream().map(cs -> cs.documentSelfLink)
                    .collect(Collectors.toList());
            redeployedContainersPerContextId.put(
                    containerStates.get(0).customProperties.get(RequestUtils.FIELD_NAME_CONTEXT_ID_KEY),
                    containersFromDesc1);
        });

        if (containerFromDesc1Redeployed.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 containerFromDesc1Redeployed.get();
    });
}

From source file:com.liveramp.hank.test.ZkTestCase.java

@Before
public final void setUpZk() throws Exception {

    setupZkServer();//from ww  w  .j a  va 2s  .  c om

    final Object lock = new Object();
    final AtomicBoolean connected = new AtomicBoolean(false);

    zk = new ZooKeeperPlus("127.0.0.1:" + zkClientPort, 1000000, new Watcher() {
        @Override
        public void process(WatchedEvent event) {
            switch (event.getType()) {
            case None:
                if (event.getState() == KeeperState.SyncConnected) {
                    connected.set(true);
                    synchronized (lock) {
                        lock.notifyAll();
                    }
                }
            }
            LOG.debug(event.toString());
        }
    });

    synchronized (lock) {
        lock.wait(2000);
    }
    if (!connected.get()) {
        fail("timed out waiting for the zk client connection to come online!");
    }
    LOG.debug("session timeout: " + zk.getSessionTimeout());

    zk.deleteNodeRecursively(zkRoot);
    WaitUntil.orDie(() -> {
        try {
            return zk.exists(zkRoot, false) == null;
        } catch (KeeperException | InterruptedException e) {
            throw new RuntimeException(e);
        }
    });
    createNodeRecursively(zkRoot);
}

From source file:de.metas.ui.web.notification.UserNotification.java

private UserNotification(final UserNotification from) {
    super();//  w  ww .  j  a v a2 s .  c  om

    id = from.id;
    timestamp = from.timestamp;
    important = from.important;

    detailPlain = from.detailPlain;
    detailADMessage = from.detailADMessage;
    detailADMessageParams = from.detailADMessageParams;
    adLanguage2message.putAll(from.adLanguage2message);

    read = new AtomicBoolean(from.read.get());

    targetType = from.targetType;
    target_adWindowId = from.target_adWindowId;
    target_tableName = from.target_tableName;
    target_recordId = from.target_recordId;
}

From source file:ch.algotrader.service.ib.IBNativeOrderServiceImpl.java

public IBNativeOrderServiceImpl(final IBSession iBSession, final AutoIncrementIdGenerator orderIdGenerator,
        final OrderBook orderBook, final IBExecutions iBExecutions,
        final IBOrderMessageFactory iBOrderMessageFactory,
        final OrderPersistenceService orderPersistenceService, final OrderDao orderDao,
        final CommonConfig commonConfig) {

    Validate.notNull(iBSession, "IBSession is null");
    Validate.notNull(orderIdGenerator, "AutoIncrementIdGenerator is null");
    Validate.notNull(orderBook, "OpenOrderRegistry is null");
    Validate.notNull(iBExecutions, "IBExecutions is null");
    Validate.notNull(iBOrderMessageFactory, "IBOrderMessageFactory is null");
    Validate.notNull(orderPersistenceService, "OrderPersistenceService is null");
    Validate.notNull(orderDao, "OrderDao is null");
    Validate.notNull(commonConfig, "CommonConfig is null");

    this.iBSession = iBSession;
    this.orderIdGenerator = orderIdGenerator;
    this.orderBook = orderBook;
    this.iBExecutions = iBExecutions;
    this.iBOrderMessageFactory = iBOrderMessageFactory;
    this.orderPersistenceService = orderPersistenceService;
    this.orderDao = orderDao;
    this.commonConfig = commonConfig;
    this.lock = new ReentrantLock();
    this.firstTime = new AtomicBoolean(false);
}