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.adaptris.core.lms.StreamWrapperCase.java

@Test
public void testInputStream_Read() throws Exception {
    StreamWrapper wrapper = createWrapper(false);
    AtomicBoolean callback = new AtomicBoolean(false);
    File file = writeFile(TempFileUtils.createTrackedFile(wrapper));
    InputStream in = wrapper.openInputStream(file, () -> {
        callback.set(true);//  w w w . j  a  v a 2 s .c  om
    });
    try (InputStream closeable = in) {
        int read = 0;
        while (read != -1) {
            read = closeable.read();
        }
    }
    tryQuietly(() -> {
        in.close();
    });
    assertTrue(callback.get());
}

From source file:com.tobedevoured.json.SimpleStreamTest.java

@Test
public void testCallback() throws StreamException {
    final AtomicBoolean isCalledBack = new AtomicBoolean(false);
    simpleStream.setCallback(new Function<Object, Object>() {

        @Override/*w  ww  .  jav a  2s .com*/
        public Object apply(Object entity) {
            assertNotNull(entity);
            isCalledBack.set(true);
            return null;
        }
    });

    simpleStream.stream("{\"test\": \"this is a test\"} [1,2,3]");
    List entities = simpleStream.flush();

    assertTrue("callback was called", isCalledBack.get());

    Map<String, String> expectedEntity = ImmutableMap.of("test", "this is a test");
    assertEquals(expectedEntity, entities.get(0));

    assertEquals(Arrays.asList(1L, 2L, 3L), entities.get(1));
}

From source file:com.spectralogic.ds3client.helpers.FileObjectPutter_Test.java

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

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

    final String A_FILE_NAME = "aFile.txt";

    final AtomicBoolean caughtException = new AtomicBoolean(false);

    try {/*www.  ja  va 2 s.c o m*/
        Files.createFile(Paths.get(tempDirectory.toString(), A_FILE_NAME));
        new FileObjectPutter(tempDirectory).buildChannel(A_FILE_NAME);
    } catch (final UnrecoverableIOException e) {
        assertTrue(e.getMessage().contains(A_FILE_NAME));
        caughtException.set(true);
    } finally {
        FileUtils.deleteDirectory(tempDirectory.toFile());
    }

    assertFalse(caughtException.get());
}

From source file:ch.cyberduck.core.local.FinderLocalTest.java

@Test
public void testReleaseSecurityScopeBookmarkInputStreamClose() throws Exception {
    final AtomicBoolean released = new AtomicBoolean(false);
    FinderLocal l = new FinderLocal(System.getProperty("java.io.tmpdir"), UUID.randomUUID().toString()) {
        @Override// ww w . ja v a  2 s.  c  o  m
        public void release(final Object lock) {
            released.set(true);
            super.release(lock);
        }
    };
    new DefaultLocalTouchFeature().touch(l);
    final InputStream in = l.getInputStream();
    in.close();
    assertTrue(released.get());
    l.delete();
}

From source file:org.apache.hadoop.hbase.regionserver.TestRSKilledWhenInitializing.java

/**
 * Start Master. Get as far as the state where Master is waiting on
 * RegionServers to check in, then return.
 *//*  w  w  w .j  av  a 2  s  . c  o  m*/
private MasterThread startMaster(MasterThread master) {
    master.start();
    // It takes a while until ServerManager creation to happen inside Master startup.
    while (master.getMaster().getServerManager() == null) {
        continue;
    }
    // Set a listener for the waiting-on-RegionServers state. We want to wait
    // until this condition before we leave this method and start regionservers.
    final AtomicBoolean waiting = new AtomicBoolean(false);
    if (master.getMaster().getServerManager() == null)
        throw new NullPointerException("SM");
    master.getMaster().getServerManager().registerListener(new ServerListener() {
        @Override
        public void waiting() {
            waiting.set(true);
        }
    });
    // Wait until the Master gets to place where it is waiting on RegionServers to check in.
    while (!waiting.get()) {
        continue;
    }
    // Set the global master-is-active; gets picked up by regionservers later.
    masterActive.set(true);
    return master;
}

From source file:org.alfresco.repo.activities.post.cleanup.PostCleaner.java

public void execute() throws JobExecutionException {
    final AtomicBoolean keepGoing = new AtomicBoolean(true);
    String lockToken = null;//from   w w w  .  j av a 2s  .  c o  m
    try {
        // Lock
        lockToken = jobLockService.getLock(LOCK_QNAME, LOCK_TTL);
        // Refresh to get callbacks
        JobLockRefreshCallback callback = new JobLockRefreshCallback() {
            @Override
            public void lockReleased() {
                keepGoing.set(false);
            }

            @Override
            public boolean isActive() {
                return keepGoing.get();
            }
        };
        jobLockService.refreshLock(lockToken, LOCK_QNAME, LOCK_TTL, callback);

        executeWithLock();
    } catch (LockAcquisitionException e) {
        if (logger.isDebugEnabled()) {
            logger.debug("Skipping post cleaning.  " + e.getMessage());
        }
    } finally {
        keepGoing.set(false); // Notify the refresh callback that we are done
        if (lockToken != null) {
            jobLockService.releaseLock(lockToken, LOCK_QNAME);
        }
    }
}

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

/**
 * Add this reader to the reader group so that it is able to acquire segments
 *///from www.  j a  va  2  s .  c om
void initializeReader(long initialAllocationDelay) {
    AtomicBoolean alreadyAdded = new AtomicBoolean(false);
    sync.updateState(state -> {
        if (state.getSegments(readerId) == null) {
            return Collections.singletonList(new AddReader(readerId));
        } else {
            alreadyAdded.set(true);
            return null;
        }
    });
    if (alreadyAdded.get()) {
        throw new IllegalStateException("The requested reader: " + readerId
                + " cannot be added to the group because it is already in the group. Perhaps close() was not called?");
    }
    long randomDelay = (long) (RandomUtils.nextFloat()
            * Math.min(initialAllocationDelay, sync.getState().getConfig().getGroupRefreshTimeMillis()));
    acquireTimer.reset(Duration.ofMillis(initialAllocationDelay + randomDelay));
}

From source file:org.apache.any23.extractor.microdata.MicrodataParserTest.java

@Test
public void testGetDateConcurrent() throws Exception {
    final Date expectedDate = new GregorianCalendar(2009, Calendar.MAY, 10).getTime(); // 2009-05-10
    final byte[] content = IOUtils
            .toByteArray(getClass().getResourceAsStream("/microdata/microdata-basic.html"));
    final int threadCount = 10;
    final int attemptCount = 100;
    final List<Thread> threads = new ArrayList<Thread>();
    final CountDownLatch beforeLatch = new CountDownLatch(1);
    final CountDownLatch afterLatch = new CountDownLatch(threadCount);
    final AtomicBoolean foundFailure = new AtomicBoolean(false);
    for (int i = 0; i < threadCount; i++) {
        threads.add(new Thread("Test-thread-" + i) {
            @Override//from  w w w .j a v  a  2  s  .com
            public void run() {
                try {
                    beforeLatch.await();
                    int counter = 0;
                    while (counter++ < attemptCount && !foundFailure.get()) {
                        final Document document = getDom(content);
                        final MicrodataParserReport report = MicrodataParser.getMicrodata(document);
                        final ItemScope target = report.getDetectedItemScopes()[4];
                        Date actualDate = target.getProperties().get("birthday").get(0).getValue().getAsDate();
                        if (!expectedDate.equals(actualDate)) {
                            foundFailure.set(true);
                        }
                    }
                } catch (Exception ex) {
                    ex.printStackTrace();
                    foundFailure.set(true);
                } finally {
                    afterLatch.countDown();
                }
            }
        });
    }
    for (Thread thread : threads) {
        thread.start();
    }
    // Let threads start computation
    beforeLatch.countDown();
    // Wait for all threads to complete
    afterLatch.await();
    assertFalse(foundFailure.get());
}

From source file:com.spectralogic.ds3client.helpers.FileObjectPutter_Test.java

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

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

    final String FIFO_NAME = "bFifo";

    final AtomicBoolean caughtException = new AtomicBoolean(false);

    try {/*from w ww. j  a v  a 2s .  com*/
        Runtime.getRuntime().exec("mkfifo " + Paths.get(tempDirectory.toString(), FIFO_NAME)).waitFor();
        new FileObjectPutter(tempDirectory).buildChannel(FIFO_NAME);
    } catch (final UnrecoverableIOException e) {
        assertTrue(e.getMessage().contains(FIFO_NAME));
        caughtException.set(true);
    } finally {
        FileUtils.deleteDirectory(tempDirectory.toFile());
    }

    assertTrue(caughtException.get());
}

From source file:org.apache.hadoop.hive.ql.txn.compactor.TestCleaner.java

@Test
public void notBlockedBySubsequentLock() throws Exception {
    Table t = newTable("default", "bblt", false);

    // Set the run frequency low on this test so it doesn't take long
    conf.setTimeVar(HiveConf.ConfVars.HIVE_COMPACTOR_CLEANER_RUN_INTERVAL, 100, TimeUnit.MILLISECONDS);

    addBaseFile(t, null, 20L, 20);/*  w  w  w .  jav  a 2  s  .  co  m*/
    addDeltaFile(t, null, 21L, 22L, 2);
    addDeltaFile(t, null, 23L, 24L, 2);
    addDeltaFile(t, null, 21L, 24L, 4);

    burnThroughTransactions(25);

    CompactionRequest rqst = new CompactionRequest("default", "bblt", CompactionType.MINOR);
    txnHandler.compact(rqst);
    CompactionInfo ci = txnHandler.findNextToCompact("fred");
    txnHandler.markCompacted(ci);
    txnHandler.setRunAs(ci.id, System.getProperty("user.name"));

    LockComponent comp = new LockComponent(LockType.SHARED_READ, LockLevel.TABLE, "default");
    comp.setTablename("bblt");
    List<LockComponent> components = new ArrayList<LockComponent>(1);
    components.add(comp);
    LockRequest req = new LockRequest(components, "me", "localhost");
    LockResponse res = txnHandler.lock(req);

    AtomicBoolean looped = new AtomicBoolean();
    looped.set(false);
    startCleaner(looped);

    // Make sure the compactor has a chance to run once
    while (!looped.get()) {
        Thread.currentThread().sleep(100);
    }

    // There should still be one request, as the locks still held.
    ShowCompactResponse rsp = txnHandler.showCompact(new ShowCompactRequest());
    List<ShowCompactResponseElement> compacts = rsp.getCompacts();
    Assert.assertEquals(1, compacts.size());

    // obtain a second lock.  This shouldn't block cleaner as it was acquired after the initial
    // clean request
    LockComponent comp2 = new LockComponent(LockType.SHARED_READ, LockLevel.TABLE, "default");
    comp2.setTablename("bblt");
    List<LockComponent> components2 = new ArrayList<LockComponent>(1);
    components2.add(comp2);
    LockRequest req2 = new LockRequest(components, "me", "localhost");
    LockResponse res2 = txnHandler.lock(req2);

    // Unlock the previous lock
    txnHandler.unlock(new UnlockRequest(res.getLockid()));
    looped.set(false);

    while (!looped.get()) {
        Thread.currentThread().sleep(100);
    }
    stopThread();
    Thread.currentThread().sleep(200);

    // Check there are no compactions requests left.
    rsp = txnHandler.showCompact(new ShowCompactRequest());
    compacts = rsp.getCompacts();
    Assert.assertEquals(0, compacts.size());
}