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:org.elasticsearch.client.sniff.SnifferTests.java

/**
 * Test that {@link Sniffer#close()} shuts down the underlying {@link Scheduler}, and that such calls are idempotent.
 * Also verifies that the next scheduled round gets cancelled.
 *///  w w  w .ja  v a2 s .c  o  m
public void testClose() {
    final Future<?> future = mock(Future.class);
    long sniffInterval = randomLongBetween(1, Long.MAX_VALUE);
    long sniffAfterFailureDelay = randomLongBetween(1, Long.MAX_VALUE);
    RestClient restClient = mock(RestClient.class);
    final AtomicInteger shutdown = new AtomicInteger(0);
    final AtomicBoolean initialized = new AtomicBoolean(false);
    Scheduler scheduler = new Scheduler() {
        @Override
        public Future<?> schedule(Sniffer.Task task, long delayMillis) {
            if (initialized.compareAndSet(false, true)) {
                //run from the same thread so the sniffer gets for sure initialized and the scheduled task gets cancelled on close
                task.run();
            }
            return future;
        }

        @Override
        public void shutdown() {
            shutdown.incrementAndGet();
        }
    };

    Sniffer sniffer = new Sniffer(restClient, new MockHostsSniffer(), scheduler, sniffInterval,
            sniffAfterFailureDelay);
    assertEquals(0, shutdown.get());
    int iters = randomIntBetween(3, 10);
    for (int i = 1; i <= iters; i++) {
        sniffer.close();
        verify(future, times(i)).cancel(false);
        assertEquals(i, shutdown.get());
    }
}

From source file:com.example.app.ui.DemoUserProfileEditor.java

@Override
public boolean validateUIValue(final Notifiable notifiable) {
    final AtomicBoolean valid = new AtomicBoolean(true);
    _forEach(value -> valid.set(value.validateUIValue(notifiable) && valid.get()));
    return valid.get();
}

From source file:com.jivesoftware.os.amza.service.storage.binary.BinaryRowReaderWriterTest.java

@Test(enabled = false)
public void testConcurrency() throws Exception {
    MemoryBackedWALFiler walFiler = new MemoryBackedWALFiler(
            new MultiAutoGrowingByteBufferBackedFiler(32, 1_024 * 1_024, new HeapByteBufferFactory()));
    IoStats ioStats = new IoStats();
    BinaryRowReader binaryRowReader = new BinaryRowReader(walFiler);
    BinaryRowWriter binaryRowWriter = new BinaryRowWriter(walFiler);

    ExecutorService executors = Executors.newFixedThreadPool(9);
    AtomicBoolean running = new AtomicBoolean(true);
    AtomicLong scanned = new AtomicLong();
    List<Future<?>> futures = Lists.newArrayList();
    for (int i = 0; i < 8; i++) {
        futures.add(executors.submit(() -> {
            try {
                while (running.get()) {
                    binaryRowReader.scan(ioStats, 0, false, (rowFP, rowTxId, rowType, row) -> {
                        scanned.incrementAndGet();
                        return true;
                    });//from w  ww .j av a 2s .com
                }
                return true;
            } catch (Throwable t) {
                t.printStackTrace();
                throw t;
            }
        }));
    }
    futures.add(executors.submit(() -> {
        try {
            for (int i = 0; i < 1_000_000; i++) {
                byte[] row = UIO.intBytes(i);
                binaryRowWriter.write(ioStats, i, RowType.primary, 1, 16, stream -> stream.stream(row),
                        stream -> true,
                        (txId, prefix, key, value, valueTimestamp, valueTombstoned, valueVersion, fp) -> true,
                        false, false);
                if (i % 10_000 == 0) {
                    System.out.println("Finished i:" + i + " scanned:" + scanned.get());
                }
            }
        } finally {
            running.set(false);
        }
        return null;
    }));

    for (Future<?> future : futures) {
        future.get();
    }
}

From source file:com.linkedin.helix.store.file.FilePropertyStore.java

public FilePropertyStore(final PropertySerializer<T> serializer, String rootNamespace,
        final PropertyJsonComparator<T> comparator) {
    _serializer = serializer;//from   ww  w.ja  v a2s . c om
    _comparator = comparator;
    _stopRefreshThread = new AtomicBoolean(false);
    _firstRefreshCounter = new CountDownLatch(1);
    _readWriteLock = new ReentrantReadWriteLock();

    _fileChangeListeners = new ConcurrentHashMap<String, CopyOnWriteArraySet<PropertyChangeListener<T>>>();

    // Strip off leading slash
    while (rootNamespace.startsWith("/")) {
        // rootNamespace = rootNamespace.substring(1, rootNamespace.length());
        rootNamespace = rootNamespace.substring(1);
    }
    _rootNamespace = "/" + rootNamespace;

    this.createRootNamespace();
}

From source file:com.datatorrent.stram.engine.GenericNodeTest.java

@Test
public void testPrematureTermination() throws InterruptedException {
    long maxSleep = 5000;
    long sleeptime = 25L;
    GenericOperator go = new GenericOperator();
    final GenericNode gn = new GenericNode(go,
            new com.datatorrent.stram.engine.OperatorContext(0, new DefaultAttributeMap(), null));
    gn.setId(1);/*from   w  w  w  .  j a  v a 2  s .co m*/
    AbstractReservoir reservoir1 = AbstractReservoir.newReservoir("ip1Res", 1024);
    AbstractReservoir reservoir2 = AbstractReservoir.newReservoir("ip2Res", 1024);

    gn.connectInputPort("ip1", reservoir1);
    gn.connectInputPort("ip2", reservoir2);
    gn.connectOutputPort("op", Sink.BLACKHOLE);
    gn.firstWindowMillis = 0;
    gn.windowWidthMillis = 100;

    final AtomicBoolean ab = new AtomicBoolean(false);
    Thread t = new Thread() {
        @Override
        public void run() {
            ab.set(true);
            gn.activate();
            gn.run();
            gn.deactivate();
        }

    };
    t.start();

    long interval = 0;
    do {
        Thread.sleep(sleeptime);
        interval += sleeptime;
    } while ((ab.get() == false) && (interval < maxSleep));

    int controlTupleCount = gn.controlTupleCount;
    Tuple beginWindow1 = new Tuple(MessageType.BEGIN_WINDOW, 0x1L);

    reservoir1.add(beginWindow1);
    reservoir2.add(beginWindow1);

    interval = 0;
    do {
        Thread.sleep(sleeptime);
        interval += sleeptime;
    } while ((gn.controlTupleCount == controlTupleCount) && (interval < maxSleep));
    Assert.assertTrue("Begin window called", go.endWindowId != go.beginWindowId);
    controlTupleCount = gn.controlTupleCount;

    Tuple endWindow1 = new EndWindowTuple(0x1L);

    reservoir1.add(endWindow1);
    reservoir2.add(endWindow1);

    interval = 0;
    do {
        Thread.sleep(sleeptime);
        interval += sleeptime;
    } while ((gn.controlTupleCount == controlTupleCount) && (interval < maxSleep));
    Assert.assertTrue("End window called", go.endWindowId == go.beginWindowId);
    controlTupleCount = gn.controlTupleCount;

    Tuple beginWindow2 = new Tuple(MessageType.BEGIN_WINDOW, 0x2L);

    reservoir1.add(beginWindow2);
    reservoir2.add(beginWindow2);

    interval = 0;
    do {
        Thread.sleep(sleeptime);
        interval += sleeptime;
    } while ((gn.controlTupleCount == controlTupleCount) && (interval < maxSleep));

    gn.shutdown();
    t.join();

    Assert.assertTrue("End window not called", go.endWindowId != go.beginWindowId);
}

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

@Test
public void createReadJobWithBigFile() throws IOException, URISyntaxException, NoSuchMethodException,
        IllegalAccessException, InvocationTargetException {
    final String tempPathPrefix = null;
    final Path tempDirectory = Files.createTempDirectory(Paths.get("."), tempPathPrefix);

    try {/*from ww w .  ja v  a 2s .  c  o  m*/
        final String DIR_NAME = "largeFiles/";
        final String FILE_NAME = "lesmis-copies.txt";

        final Path objPath = ResourceUtils.loadFileResource(DIR_NAME + FILE_NAME);
        final long bookSize = Files.size(objPath);
        final Ds3Object obj = new Ds3Object(FILE_NAME, bookSize);

        final Ds3ClientShim ds3ClientShim = new Ds3ClientShim((Ds3ClientImpl) client);

        final int maxNumBlockAllocationRetries = 1;
        final int maxNumObjectTransferAttempts = 3;
        final Ds3ClientHelpers ds3ClientHelpers = Ds3ClientHelpers.wrap(ds3ClientShim,
                maxNumBlockAllocationRetries, maxNumObjectTransferAttempts);

        final Ds3ClientHelpers.Job readJob = ds3ClientHelpers.startReadJob(BUCKET_NAME, Arrays.asList(obj));

        final AtomicBoolean dataTransferredEventReceived = new AtomicBoolean(false);
        final AtomicBoolean objectCompletedEventReceived = new AtomicBoolean(false);
        final AtomicBoolean checksumEventReceived = new AtomicBoolean(false);
        final AtomicBoolean metadataEventReceived = new AtomicBoolean(false);
        final AtomicBoolean waitingForChunksEventReceived = new AtomicBoolean(false);
        final AtomicBoolean failureEventReceived = new AtomicBoolean(false);

        readJob.attachDataTransferredListener(new DataTransferredListener() {
            @Override
            public void dataTransferred(final long size) {
                dataTransferredEventReceived.set(true);
                assertEquals(bookSize, size);
            }
        });
        readJob.attachObjectCompletedListener(new ObjectCompletedListener() {
            @Override
            public void objectCompleted(final String name) {
                objectCompletedEventReceived.set(true);
            }
        });
        readJob.attachChecksumListener(new ChecksumListener() {
            @Override
            public void value(final BulkObject obj, final ChecksumType.Type type, final String checksum) {
                checksumEventReceived.set(true);
                assertEquals("0feqCQBgdtmmgGs9pB/Huw==", checksum);
            }
        });
        readJob.attachMetadataReceivedListener(new MetadataReceivedListener() {
            @Override
            public void metadataReceived(final String filename, final Metadata metadata) {
                metadataEventReceived.set(true);
            }
        });
        readJob.attachWaitingForChunksListener(new WaitingForChunksListener() {
            @Override
            public void waiting(final int secondsToWait) {
                waitingForChunksEventReceived.set(true);
            }
        });
        readJob.attachFailureEventListener(new FailureEventListener() {
            @Override
            public void onFailure(final FailureEvent failureEvent) {
                failureEventReceived.set(true);
            }
        });

        final GetJobSpectraS3Response jobSpectraS3Response = ds3ClientShim
                .getJobSpectraS3(new GetJobSpectraS3Request(readJob.getJobId()));

        assertThat(jobSpectraS3Response.getMasterObjectListResult(), is(notNullValue()));

        readJob.transfer(new FileObjectGetter(tempDirectory));

        final File originalFile = ResourceUtils.loadFileResource(DIR_NAME + FILE_NAME).toFile();
        final File fileCopiedFromBP = Paths.get(tempDirectory.toString(), FILE_NAME).toFile();
        assertTrue(FileUtils.contentEquals(originalFile, fileCopiedFromBP));

        assertTrue(dataTransferredEventReceived.get());
        assertTrue(objectCompletedEventReceived.get());
        assertTrue(checksumEventReceived.get());
        assertTrue(metadataEventReceived.get());
        assertFalse(waitingForChunksEventReceived.get());
        assertFalse(failureEventReceived.get());
    } finally {
        FileUtils.deleteDirectory(tempDirectory.toFile());
    }
}

From source file:org.lendingclub.mercator.docker.SwarmScanner.java

public void scanServicesForSwarm(String swarmClusterId) {

    JsonNode response = getRestClient().getServices();

    AtomicLong earlistUpdate = new AtomicLong(Long.MAX_VALUE);
    AtomicBoolean error = new AtomicBoolean(false);
    response.forEach(it -> {//from www  .  j a va  2  s  .co  m
        try {
            ObjectNode n = flattenService(it);
            n.put("swarmClusterId", swarmClusterId);
            dockerScanner.getNeoRxClient().execCypher(
                    "merge (x:DockerService {serviceId:{serviceId}}) set x+={props}, x.updateTs=timestamp() return x",
                    "serviceId", n.get("serviceId").asText(), "props", n).forEach(svc -> {
                        removeDockerLabels("DockerService", "serviceId", n.get("serviceId").asText(), n, svc);
                        earlistUpdate.set(
                                Math.min(earlistUpdate.get(), svc.path("updateTs").asLong(Long.MAX_VALUE)));
                    });
            dockerScanner.getNeoRxClient().execCypher(
                    "match (swarm:DockerSwarm {swarmClusterId:{swarmClusterId}}),(service:DockerService{serviceId:{serviceId}}) merge (swarm)-[x:CONTAINS]->(service) set x.updateTs=timestamp()",
                    "swarmClusterId", swarmClusterId, "serviceId", n.path("serviceId").asText());

        } catch (Exception e) {
            logger.warn("problem updating service", e);
            error.set(true);
        }
    });
    if (error.get() == false) {
        if (earlistUpdate.get() < System.currentTimeMillis()) {
            dockerScanner.getNeoRxClient().execCypher(
                    "match (x:DockerService) where x.swarmClusterId={swarmClusterId} and x.updateTs<{cutoff} detach delete x",
                    "cutoff", earlistUpdate.get(), "swarmClusterId", swarmClusterId);
        }
    }

}

From source file:com.all.messengine.impl.DefaultMessEngine.java

public DefaultMessEngine() {
    queue = new LinkedBlockingQueue<Message<?>>();
    messageExecutor = Executors.newCachedThreadPool();
    engineExecutor = Executors.newSingleThreadExecutor();
    listeners = new HashMap<String, List<MessageListener<? extends Message<?>>>>();
    responseManager = new ResponseManager();
    shuttingDown = new AtomicBoolean(false);
}

From source file:de.hybris.platform.test.TransactionTest.java

@Test
public void testItemUpdateDuringCommit_PLA10839() throws Exception {
    final Title title1 = UserManager.getInstance().createTitle("t1");
    final Title title2 = UserManager.getInstance().createTitle("t2");
    final Title title3 = UserManager.getInstance().createTitle("t3");
    final Title title4 = UserManager.getInstance().createTitle("t4");

    final AtomicBoolean listenerHasBeenCalled = new AtomicBoolean(false);

    final InvalidationListener listener = new InvalidationListener() {
        @Override/*from w  w w.ja  v a2 s. c om*/
        public void keyInvalidated(final Object[] key, final int invalidationType,
                final InvalidationTarget target, final RemoteInvalidationSource remoteSrc) {
            listenerHasBeenCalled.set(true);
            // change t1 here
            title1.setName("newOne");
        }
    };
    final InvalidationTopic topic = InvalidationManager.getInstance()
            .getInvalidationTopic(new Object[] { Cache.CACHEKEY_HJMP, Cache.CACHEKEY_ENTITY });
    try {
        topic.addInvalidationListener(listener);

        final Transaction tx = Transaction.current();
        tx.execute(new TransactionBody() {

            @Override
            public Object execute() throws Exception {
                title2.setName("foo");
                title3.setName("foo");
                title4.setName("foo");
                return null;
            }
        });
        assertEquals("foo", title2.getName());
        assertEquals("foo", title3.getName());
        assertEquals("foo", title4.getName());
        assertEquals("newOne", title1.getName());
        assertTrue(listenerHasBeenCalled.get());
    } finally {
        topic.removeInvalidationListener(listener);
    }
}

From source file:io.atomix.protocols.gossip.map.AntiEntropyMapDelegate.java

@Override
public V put(K key, V value) {
    checkState(!closed, destroyedMessage);
    checkNotNull(key, ERROR_NULL_KEY);/* ww  w  .j av a 2s.  c  o  m*/
    checkNotNull(value, ERROR_NULL_VALUE);

    String encodedKey = encodeKey(key);
    byte[] encodedValue = encodeValue(value);

    MapValue newValue = new MapValue(encodedValue, timestampProvider.get(Maps.immutableEntry(key, value)));

    counter.incrementCount();
    AtomicReference<byte[]> oldValue = new AtomicReference<>();
    AtomicBoolean updated = new AtomicBoolean(false);
    items.compute(encodedKey, (k, existing) -> {
        if (existing == null || newValue.isNewerThan(existing)) {
            updated.set(true);
            oldValue.set(existing != null ? existing.get() : null);
            return newValue;
        }
        return existing;
    });

    if (updated.get()) {
        notifyPeers(new UpdateEntry(encodedKey, newValue),
                peerUpdateFunction.select(Maps.immutableEntry(key, value), membershipService));
        if (oldValue.get() == null) {
            notifyListeners(new MapDelegateEvent<>(INSERT, key, value));
        } else {
            notifyListeners(new MapDelegateEvent<>(UPDATE, key, value));
        }
        return decodeValue(oldValue.get());
    }
    return value;
}