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:com.arpnetworking.metrics.impl.ApacheHttpSinkTest.java

@Test
public void testBatchesRequests() throws InterruptedException {
    _wireMockRule.stubFor(WireMock.requestMatching(new RequestValueMatcher(r -> {
        // Annotations
        Assert.assertEquals(0, r.getAnnotationsCount());

        // Dimensions
        Assert.assertEquals(0, r.getDimensionsCount());

        // Samples
        assertSample(r.getTimersList(), "timer", 7d);
        assertSample(r.getCountersList(), "counter", 8d);
        assertSample(r.getGaugesList(), "gauge", 9d);
    })).willReturn(WireMock.aResponse().withStatus(200)));

    final AtomicBoolean assertionResult = new AtomicBoolean(false);
    final Semaphore semaphore = new Semaphore(0);
    final Sink sink = new ApacheHttpSink.Builder()
            .setUri(URI.create("http://localhost:" + _wireMockRule.port() + PATH)).setMaxBatchSize(10)
            .setParallelism(1).setEmptyQueueInterval(Duration.ofMillis(1000))
            .setEventHandler(new AttemptCompletedAssertionHandler(assertionResult, 3, 210, true,
                    new CompletionHandler(semaphore)))
            .build();//w ww. j av  a  2 s  .  c  om

    final TsdEvent event = new TsdEvent(Collections.emptyMap(),
            createQuantityMap("timer", TsdQuantity.newInstance(7d, null)),
            createQuantityMap("counter", TsdQuantity.newInstance(8d, null)),
            createQuantityMap("gauge", TsdQuantity.newInstance(9d, null)));

    for (int x = 0; x < 3; x++) {
        sink.record(event);
    }
    semaphore.acquire();

    // Ensure expected handler was invoked
    Assert.assertTrue(assertionResult.get());

    // Request matcher
    final RequestPatternBuilder requestPattern = WireMock.postRequestedFor(WireMock.urlEqualTo(PATH))
            .withHeader("Content-Type", WireMock.equalTo("application/octet-stream"));

    // Assert that data was sent
    _wireMockRule.verify(1, requestPattern);
    Assert.assertTrue(_wireMockRule.findUnmatchedRequests().getRequests().isEmpty());
}

From source file:com.github.vatbub.tictactoe.view.Main.java

private void connectToRelayServer() {
    setLoadingStatusText("The server is waking up, hang tight...", true);
    showLoadingScreen();/*www.j  av  a 2  s  .  c  om*/
    Thread connectionThread = new Thread(() -> {
        int maxRetries = 10;
        int remainingRetries = maxRetries;
        AtomicBoolean readyWithoutException = new AtomicBoolean(false);
        Exception lastException = null;

        while (remainingRetries > 0 && !readyWithoutException.get()) {
            try {
                int finalRemainingRetries = remainingRetries;
                KryoGameConnections.connect(() -> {
                    if (maxRetries == finalRemainingRetries)
                        // should only appear the first time
                        setLoadingStatusText("Connecting to the server...");
                }, () -> Platform.runLater(() -> {
                    readyWithoutException.set(true);
                    hideLoadingScreen();
                    showOnlineMenu();
                }));
            } catch (Exception e) {
                remainingRetries--;
                setLoadingStatusText("This is taking longer than usual, hang tight (Retry "
                        + (maxRetries - remainingRetries) + " of " + maxRetries + ")...");
                FOKLogger.log(Main.class.getName(), Level.SEVERE,
                        "Could not connect to the relay server: " + e.getMessage(), e);
                lastException = e;
            }
        }

        if (!readyWithoutException.get()) {
            if (lastException == null) {
                Platform.runLater(() -> showErrorMessage("Something went wrong.", "Unknown"));
            } else {
                Exception finalLastException = lastException;
                Platform.runLater(() -> showErrorMessage(finalLastException));
            }
        }
    });
    connectionThread.setName("connectionThread");
    connectionThread.start();
}

From source file:org.apache.hadoop.hdfs.client.impl.TestBlockReaderFactory.java

/**
 * Test the case where we have multiple threads waiting on the
 * ShortCircuitCache delivering a certain ShortCircuitReplica.
 *
 * In this case, there should only be one call to
 * createShortCircuitReplicaInfo.  This one replica should be shared
 * by all threads./*  w  w w.j a  v a  2 s.co m*/
 */
@Test(timeout = 60000)
public void testMultipleWaitersOnShortCircuitCache() throws Exception {
    final CountDownLatch latch = new CountDownLatch(1);
    final AtomicBoolean creationIsBlocked = new AtomicBoolean(true);
    final AtomicBoolean testFailed = new AtomicBoolean(false);
    DFSInputStream.tcpReadsDisabledForTesting = true;
    BlockReaderFactory.createShortCircuitReplicaInfoCallback = new ShortCircuitCache.ShortCircuitReplicaCreator() {
        @Override
        public ShortCircuitReplicaInfo createShortCircuitReplicaInfo() {
            Uninterruptibles.awaitUninterruptibly(latch);
            if (!creationIsBlocked.compareAndSet(true, false)) {
                Assert.fail("there were multiple calls to "
                        + "createShortCircuitReplicaInfo.  Only one was expected.");
            }
            return null;
        }
    };
    TemporarySocketDirectory sockDir = new TemporarySocketDirectory();
    Configuration conf = createShortCircuitConf("testMultipleWaitersOnShortCircuitCache", sockDir);
    MiniDFSCluster cluster = new MiniDFSCluster.Builder(conf).numDataNodes(1).build();
    cluster.waitActive();
    final DistributedFileSystem dfs = cluster.getFileSystem();
    final String TEST_FILE = "/test_file";
    final int TEST_FILE_LEN = 4000;
    final int SEED = 0xFADED;
    final int NUM_THREADS = 10;
    DFSTestUtil.createFile(dfs, new Path(TEST_FILE), TEST_FILE_LEN, (short) 1, SEED);
    Runnable readerRunnable = new Runnable() {
        @Override
        public void run() {
            try {
                byte contents[] = DFSTestUtil.readFileBuffer(dfs, new Path(TEST_FILE));
                Assert.assertFalse(creationIsBlocked.get());
                byte expected[] = DFSTestUtil.calculateFileContentsFromSeed(SEED, TEST_FILE_LEN);
                Assert.assertTrue(Arrays.equals(contents, expected));
            } catch (Throwable e) {
                LOG.error("readerRunnable error", e);
                testFailed.set(true);
            }
        }
    };
    Thread threads[] = new Thread[NUM_THREADS];
    for (int i = 0; i < NUM_THREADS; i++) {
        threads[i] = new Thread(readerRunnable);
        threads[i].start();
    }
    Thread.sleep(500);
    latch.countDown();
    for (int i = 0; i < NUM_THREADS; i++) {
        Uninterruptibles.joinUninterruptibly(threads[i]);
    }
    cluster.shutdown();
    sockDir.close();
    Assert.assertFalse(testFailed.get());
}

From source file:com.jayway.maven.plugins.android.AbstractAndroidMojo.java

/**
 * Undeploys an apk, specified by package name, from a connected emulator
 * or usb device. Also deletes the application's data and cache
 * directories on the device.// www . j  ava2 s  .c o m
 *
 * @param packageName the package name to undeploy.
 * @return <code>true</code> if successfully undeployed, <code>false</code> otherwise.
 */
protected boolean undeployApk(final String packageName) throws MojoExecutionException, MojoFailureException {

    final AtomicBoolean result = new AtomicBoolean(true); // if no devices are present, it counts as successful

    doWithDevices(new DeviceCallback() {
        public void doWithDevice(final IDevice device) throws MojoExecutionException {
            String deviceLogLinePrefix = DeviceHelper.getDeviceLogLinePrefix(device);
            try {
                device.uninstallPackage(packageName);
                getLog().info(deviceLogLinePrefix + "Successfully uninstalled " + packageName);
                getLog().debug(" from " + DeviceHelper.getDescriptiveName(device));
                result.set(true);
            } catch (InstallException e) {
                result.set(false);
                throw new MojoExecutionException(
                        deviceLogLinePrefix + "Uninstall of " + packageName + " failed.", e);
            }
        }
    });

    return result.get();
}

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

@Test
public void testThatFifoIsNotProcessed() throws IOException, InterruptedException {
    Assume.assumeFalse(Platform.isWindows());

    final String tempPathPrefix = null;
    final Path tempDirectory = Files.createTempDirectory(Paths.get("."), tempPathPrefix);

    final String BEOWULF_FILE_NAME = "beowulf.txt";

    final AtomicBoolean caughtException = new AtomicBoolean(false);

    try {// ww w  .ja v  a2  s.  c  o  m
        Runtime.getRuntime().exec("mkfifo " + Paths.get(tempDirectory.toString(), BEOWULF_FILE_NAME)).waitFor();

        final List<Ds3Object> ds3Objects = Arrays.asList(new Ds3Object(BEOWULF_FILE_NAME));

        final Ds3ClientHelpers.Job readJob = HELPERS.startReadJob(BUCKET_NAME, ds3Objects);
        readJob.transfer(new FileObjectPutter(tempDirectory));
    } catch (final UnrecoverableIOException e) {
        assertTrue(e.getMessage().contains(BEOWULF_FILE_NAME));
        caughtException.set(true);
    } finally {
        FileUtils.deleteDirectory(tempDirectory.toFile());
    }

    assertTrue(caughtException.get());
}

From source file:org.apache.nifi.processors.ocr.TesseractOCRProcessor.java

@Override
public void onTrigger(final ProcessContext context, final ProcessSession session) throws ProcessException {
    final FlowFile flowFile = session.get();
    if (flowFile == null) {
        return;/* www. java 2  s . co m*/
    }

    //Transfer the original
    session.transfer(session.clone(flowFile), REL_ORIGINAL);
    final AtomicBoolean errors = new AtomicBoolean(false);

    FlowFile ff = session.write(flowFile, new StreamCallback() {
        @Override
        public void process(InputStream inputStream, OutputStream outputStream) throws IOException {
            tesseract.setDatapath(
                    context.getProperty(TESS_DATA_PATH).evaluateAttributeExpressions(flowFile).getValue());

            //Builds the list of Tesseract configs.
            Map<String, String> configs = buildTesseractConfigs(
                    context.getProperty(TESSERACT_CONFIGS).getValue());
            for (Map.Entry<String, String> entry : configs.entrySet()) {
                getLogger().debug("Tesseract Config Key : '" + entry.getKey() + "' Tesseract Config Value : '"
                        + entry.getValue() + "'");
                tesseract.setTessVariable(entry.getKey(), entry.getValue());
            }

            try {
                BufferedImage imBuff = ImageIO.read(inputStream);
                outputStream.write(tesseract.doOCR(imBuff).getBytes());
            } catch (TesseractException te) {
                getLogger().error(te.getMessage());
                if (te.getCause().getMessage().equals("image == null!")) {
                    session.transfer(flowFile, REL_UNSUPPORTED_IMAGE_FORMAT);
                } else {
                    session.transfer(session.penalize(flowFile), REL_FAILURE);
                }
                errors.set(true);

            } catch (Exception ex) {
                getLogger().error(ex.getMessage());
                session.transfer(flowFile, REL_FAILURE);
                errors.set(true);
            }
        }
    });

    if (!errors.get()) {
        session.transfer(ff, REL_SUCCESS);
    }

}

From source file:io.pravega.client.stream.impl.ControllerImplTest.java

@Test
public void testParallelGetCurrentSegments() throws Exception {
    final ExecutorService executorService = Executors.newFixedThreadPool(10);
    Semaphore createCount = new Semaphore(-19);
    AtomicBoolean success = new AtomicBoolean(true);
    for (int i = 0; i < 10; i++) {
        executorService.submit(() -> {
            for (int j = 0; j < 2; j++) {
                try {
                    CompletableFuture<StreamSegments> streamSegments;
                    streamSegments = controllerClient.getCurrentSegments("scope1", "streamparallel");
                    assertTrue(streamSegments.get().getSegments().size() == 2);
                    assertEquals(new Segment("scope1", "streamparallel", 0),
                            streamSegments.get().getSegmentForKey(0.2));
                    assertEquals(new Segment("scope1", "streamparallel", 1),
                            streamSegments.get().getSegmentForKey(0.6));
                    createCount.release();
                } catch (Exception e) {
                    log.error("Exception when getting segments: {}", e);

                    // Don't wait for other threads to complete.
                    success.set(false);/*  www  .ja v  a  2s. co  m*/
                    createCount.release(20);
                }
            }
        });
    }
    createCount.acquire();
    executorService.shutdownNow();
    assertTrue(success.get());
}

From source file:com.gargoylesoftware.htmlunit.CodeStyleTest.java

private boolean isSvnPropertiesDefined(final File file) {
    try {/*from w w w  .  j  a  va 2  s.co  m*/
        final AtomicBoolean eol = new AtomicBoolean();
        svnWCClient_.doGetProperty(file, null, SVNRevision.WORKING, SVNRevision.WORKING, SVNDepth.EMPTY,
                new ISVNPropertyHandler() {

                    @Override
                    public void handleProperty(final long revision, final SVNPropertyData property) {
                        // nothing to do
                    }

                    @Override
                    public void handleProperty(final SVNURL url, final SVNPropertyData property) {
                        // nothing to do
                    }

                    @Override
                    public void handleProperty(final File path, final SVNPropertyData property) {
                        final String name = property.getName();
                        final String value = property.getValue().getString();
                        if ("svn:eol-style".equals(name) && "native".equals(value)) {
                            eol.set(true);
                        }
                    }
                }, null);

        final String fileName = file.getName().toLowerCase(Locale.ROOT);

        for (final String extension : SVN.getEolExtenstions()) {
            if (fileName.endsWith(extension)) {
                return eol.get();
            }
        }
        return true;
    } catch (final Exception e) {
        //nothing
    }
    final String path = file.getAbsolutePath();
    // automatically generated and is outside SVN control
    return (path.contains("jQuery") && path.contains("WEB-INF") && path.contains("cgi"))
            || (path.contains("jQuery") && path.contains("csp.log"));
}

From source file:io.pravega.segmentstore.server.containers.StreamSegmentMapperTests.java

/**
 * Tests the ability of getOrAssignStreamSegmentId to handle the TooManyActiveSegmentsException.
 *//* w  w  w  .  j  a  v a  2 s.  co m*/
@Test
public void testGetOrAssignStreamSegmentIdWithMetadataLimit() throws Exception {
    final String segmentName = "Segment";
    final String transactionName = StreamSegmentNameUtils.getTransactionNameFromId(segmentName,
            UUID.randomUUID());

    HashSet<String> storageSegments = new HashSet<>();
    storageSegments.add(segmentName);
    storageSegments.add(transactionName);

    @Cleanup
    TestContext context = new TestContext();
    setupStorageGetHandler(context, storageSegments,
            name -> new StreamSegmentInformation(name, 0, false, false, new ImmutableDate()));

    // 1. Verify the behavior when even after the retry we still cannot map.
    AtomicInteger exceptionCounter = new AtomicInteger();
    AtomicBoolean cleanupInvoked = new AtomicBoolean();

    // We use 'containerId' as a proxy for the exception id (to make sure we collect the right one).
    context.operationLog.addHandler = op -> FutureHelpers
            .failedFuture(new TooManyActiveSegmentsException(exceptionCounter.incrementAndGet(), 0));
    Supplier<CompletableFuture<Void>> noOpCleanup = () -> {
        if (!cleanupInvoked.compareAndSet(false, true)) {
            return FutureHelpers.failedFuture(new AssertionError("Cleanup invoked multiple times/"));
        }
        return CompletableFuture.completedFuture(null);
    };
    val mapper1 = new StreamSegmentMapper(context.metadata, context.operationLog, context.stateStore,
            noOpCleanup, context.storage, executorService());
    AssertExtensions.assertThrows(
            "Unexpected outcome when trying to map a segment name to a full metadata that cannot be cleaned.",
            () -> mapper1.getOrAssignStreamSegmentId(segmentName, TIMEOUT),
            ex -> ex instanceof TooManyActiveSegmentsException
                    && ((TooManyActiveSegmentsException) ex).getContainerId() == exceptionCounter.get());
    Assert.assertEquals("Unexpected number of attempts to map.", 2, exceptionCounter.get());
    Assert.assertTrue("Cleanup was not invoked.", cleanupInvoked.get());

    // Now with a transaction.
    exceptionCounter.set(0);
    cleanupInvoked.set(false);
    AssertExtensions.assertThrows(
            "Unexpected outcome when trying to map a segment name to a full metadata that cannot be cleaned.",
            () -> mapper1.getOrAssignStreamSegmentId(transactionName, TIMEOUT),
            ex -> ex instanceof TooManyActiveSegmentsException
                    && ((TooManyActiveSegmentsException) ex).getContainerId() == exceptionCounter.get());
    Assert.assertEquals("Unexpected number of attempts to map.", 2, exceptionCounter.get());
    Assert.assertTrue("Cleanup was not invoked.", cleanupInvoked.get());

    // 2. Verify the behavior when the first call fails, but the second one succeeds.
    exceptionCounter.set(0);
    cleanupInvoked.set(false);
    Supplier<CompletableFuture<Void>> workingCleanup = () -> {
        if (!cleanupInvoked.compareAndSet(false, true)) {
            return FutureHelpers.failedFuture(new AssertionError("Cleanup invoked multiple times."));
        }

        setupOperationLog(context); // Setup the OperationLog to function correctly.
        return CompletableFuture.completedFuture(null);
    };

    val mapper2 = new StreamSegmentMapper(context.metadata, context.operationLog, context.stateStore,
            workingCleanup, context.storage, executorService());
    long id = mapper2.getOrAssignStreamSegmentId(segmentName, TIMEOUT).join();
    Assert.assertEquals("Unexpected number of attempts to map.", 1, exceptionCounter.get());
    Assert.assertTrue("Cleanup was not invoked.", cleanupInvoked.get());
    Assert.assertNotEquals("No valid SegmentId assigned.", ContainerMetadata.NO_STREAM_SEGMENT_ID, id);
}

From source file:org.apache.bookkeeper.replication.TestLedgerUnderreplicationManager.java

/**
 * Test that as the hierarchy gets cleaned up, it doesn't interfere
 * with the marking of other ledgers as underreplicated
 *///  ww w  .j av  a  2 s.c  o  m
@Test(timeout = 90000)
public void testHierarchyCleanupInterference() throws Exception {
    final LedgerUnderreplicationManager replicaMgr1 = lmf1.newLedgerUnderreplicationManager();
    final LedgerUnderreplicationManager replicaMgr2 = lmf2.newLedgerUnderreplicationManager();

    final int iterations = 100;
    final AtomicBoolean threadFailed = new AtomicBoolean(false);
    Thread markUnder = new Thread() {
        public void run() {
            long l = 1;
            try {
                for (int i = 0; i < iterations; i++) {
                    replicaMgr1.markLedgerUnderreplicated(l, "localhost:3181");
                    l += 10000;
                }
            } catch (Exception e) {
                LOG.error("markUnder Thread failed with exception", e);
                threadFailed.set(true);
                return;
            }
        }
    };
    final AtomicInteger processed = new AtomicInteger(0);
    Thread markRepl = new Thread() {
        public void run() {
            try {
                for (int i = 0; i < iterations; i++) {
                    long l = replicaMgr2.getLedgerToRereplicate();
                    replicaMgr2.markLedgerReplicated(l);
                    processed.incrementAndGet();
                }
            } catch (Exception e) {
                LOG.error("markRepl Thread failed with exception", e);
                threadFailed.set(true);
                return;
            }
        }
    };
    markRepl.setDaemon(true);
    markUnder.setDaemon(true);

    markRepl.start();
    markUnder.start();
    markUnder.join();
    assertFalse("Thread failed to complete", threadFailed.get());

    int lastProcessed = 0;
    while (true) {
        markRepl.join(10000);
        if (!markRepl.isAlive()) {
            break;
        }
        assertFalse("markRepl thread not progressing", lastProcessed == processed.get());
    }
    assertFalse("Thread failed to complete", threadFailed.get());

    List<String> children = zkc1.getChildren(urLedgerPath, false);
    for (String s : children) {
        LOG.info("s: {}", s);
    }
    assertEquals("All hierarchies should be cleaned up", 0, children.size());
}