java.util.concurrent.atomic.AtomicBoolean

Here are the examples of the java api class java.util.concurrent.atomic.AtomicBoolean taken from open source projects.

1. AbstractUnitOfWorkTest#testHandlersForCurrentPhaseAreExecuted()

View license
@Test
public void testHandlersForCurrentPhaseAreExecuted() {
    AtomicBoolean prepareCommit = new AtomicBoolean();
    AtomicBoolean commit = new AtomicBoolean();
    AtomicBoolean afterCommit = new AtomicBoolean();
    AtomicBoolean cleanup = new AtomicBoolean();
    subject.onPrepareCommit( u -> subject.onPrepareCommit( i -> prepareCommit.set(true)));
    subject.onCommit( u -> subject.onCommit( i -> commit.set(true)));
    subject.afterCommit( u -> subject.afterCommit( i -> afterCommit.set(true)));
    subject.onCleanup( u -> subject.onCleanup( i -> cleanup.set(true)));
    subject.start();
    subject.commit();
    assertTrue(prepareCommit.get());
    assertTrue(commit.get());
    assertTrue(afterCommit.get());
    assertTrue(cleanup.get());
}

2. GitRebaser#executeRebaseTaskInBackground()

Project: intellij-community
Source File: GitRebaser.java
View license
private boolean executeRebaseTaskInBackground(VirtualFile root, GitLineHandler h, GitRebaseProblemDetector rebaseConflictDetector, GitTask rebaseTask) {
    final AtomicBoolean result = new AtomicBoolean();
    final AtomicBoolean failure = new AtomicBoolean();
    rebaseTask.executeInBackground(true, new GitTaskResultHandlerAdapter() {

        @Override
        protected void onSuccess() {
            result.set(true);
        }

        @Override
        protected void onCancel() {
            result.set(false);
        }

        @Override
        protected void onFailure() {
            failure.set(true);
        }
    });
    if (failure.get()) {
        result.set(handleRebaseFailure(root, h, rebaseConflictDetector));
    }
    return result.get();
}

3. BraintreeFragmentUnitTest#executesCallbacksOnlyWhenShouldRunIsTrue()

View license
@Test
public void executesCallbacksOnlyWhenShouldRunIsTrue() throws InvalidArgumentException {
    final AtomicBoolean shouldRun = new AtomicBoolean(false);
    final AtomicBoolean run = new AtomicBoolean(false);
    BraintreeFragment fragment = BraintreeFragment.newInstance(mActivity, TOKENIZATION_KEY);
    QueuedCallback callback = new QueuedCallback() {

        @Override
        public boolean shouldRun() {
            return shouldRun.get();
        }

        @Override
        public void run() {
            run.set(true);
        }
    };
    fragment.postOrQueueCallback(callback);
    assertFalse(run.get());
    shouldRun.set(true);
    fragment.flushCallbacks();
    assertTrue(run.get());
}

4. AsyncLoadingCacheTest#getFunc_absent_null_async()

Project: caffeine
Source File: AsyncLoadingCacheTest.java
View license
@CheckNoWriter
@Test(dataProvider = "caches")
@CacheSpec(loader = Loader.NULL, executor = CacheExecutor.THREADED, executorFailure = ExecutorFailure.IGNORED)
public void getFunc_absent_null_async(AsyncLoadingCache<Integer, Integer> cache, CacheContext context) {
    Integer key = context.absentKey();
    AtomicBoolean ready = new AtomicBoolean();
    AtomicBoolean done = new AtomicBoolean();
    CompletableFuture<Integer> valueFuture = cache.get(key,  k -> {
        Awaits.await().untilTrue(ready);
        return null;
    });
    valueFuture.whenComplete(( r,  e) -> done.set(true));
    ready.set(true);
    Awaits.await().untilTrue(done);
    Awaits.await().until(() -> !cache.synchronous().asMap().containsKey(context.absentKey()));
    Awaits.await().until(() -> context, both(hasMissCount(1)).and(hasHitCount(0)));
    Awaits.await().until(() -> context, both(hasLoadSuccessCount(0)).and(hasLoadFailureCount(1)));
    assertThat(valueFuture.isDone(), is(true));
    assertThat(cache.synchronous().asMap(), not(hasKey(key)));
}

5. AsyncLoadingCacheTest#getFunc_absent_failure_async()

Project: caffeine
Source File: AsyncLoadingCacheTest.java
View license
@CheckNoWriter
@Test(dataProvider = "caches")
@CacheSpec(executor = CacheExecutor.THREADED, executorFailure = ExecutorFailure.IGNORED)
public void getFunc_absent_failure_async(AsyncLoadingCache<Integer, Integer> cache, CacheContext context) {
    AtomicBoolean ready = new AtomicBoolean();
    AtomicBoolean done = new AtomicBoolean();
    CompletableFuture<Integer> valueFuture = cache.get(context.absentKey(),  k -> {
        Awaits.await().untilTrue(ready);
        throw new IllegalStateException();
    });
    valueFuture.whenComplete(( r,  e) -> done.set(true));
    ready.set(true);
    Awaits.await().untilTrue(done);
    Awaits.await().until(() -> !cache.synchronous().asMap().containsKey(context.absentKey()));
    Awaits.await().until(() -> context, both(hasMissCount(1)).and(hasHitCount(0)));
    Awaits.await().until(() -> context, both(hasLoadSuccessCount(0)).and(hasLoadFailureCount(1)));
    assertThat(valueFuture.isCompletedExceptionally(), is(true));
    assertThat(cache.getIfPresent(context.absentKey()), is(nullValue()));
}

6. EvictionTest#put_asyncWeight()

Project: caffeine
Source File: EvictionTest.java
View license
@Test(dataProvider = "caches")
@CacheSpec(implementation = Implementation.Caffeine, maximumSize = Maximum.FULL, weigher = CacheWeigher.COLLECTION, population = Population.EMPTY, keys = ReferenceType.STRONG, values = ReferenceType.STRONG)
public void put_asyncWeight(AsyncLoadingCache<Integer, List<Integer>> cache, CacheContext context, Eviction<?, ?> eviction) {
    AtomicBoolean ready = new AtomicBoolean();
    AtomicBoolean done = new AtomicBoolean();
    CompletableFuture<List<Integer>> valueFuture = CompletableFuture.supplyAsync(() -> {
        Awaits.await().untilTrue(ready);
        return ImmutableList.of(1, 2, 3, 4, 5);
    });
    valueFuture.whenComplete(( r,  e) -> done.set(true));
    cache.put(context.absentKey(), valueFuture);
    assertThat(eviction.weightedSize().getAsLong(), is(0L));
    assertThat(cache.synchronous().estimatedSize(), is(1L));
    ready.set(true);
    Awaits.await().untilTrue(done);
    Awaits.await().until(() -> eviction.weightedSize().getAsLong(), is(5L));
    Awaits.await().until(() -> cache.synchronous().estimatedSize(), is(1L));
}

7. SingleObjectCacheTests#testRefresh()

View license
public void testRefresh() {
    final AtomicInteger count = new AtomicInteger(0);
    final AtomicBoolean needsRefresh = new AtomicBoolean(true);
    SingleObjectCache<Integer> cache = new SingleObjectCache<Integer>(TimeValue.timeValueMillis(100000), 0) {

        @Override
        protected Integer refresh() {
            return count.incrementAndGet();
        }

        @Override
        protected boolean needsRefresh() {
            return needsRefresh.get();
        }
    };
    assertEquals(1, cache.getOrRefresh().intValue());
    assertEquals(2, cache.getOrRefresh().intValue());
    needsRefresh.set(false);
    assertEquals(2, cache.getOrRefresh().intValue());
    needsRefresh.set(true);
    assertEquals(3, cache.getOrRefresh().intValue());
}

8. UriNotifierTest#testUriNotifyParentAndDescendant()

Project: squidb
Source File: UriNotifierTest.java
View license
public void testUriNotifyParentAndDescendant() {
    AtomicBoolean notifyCalled = listenTo(Uri.withAppendedPath(CONTENT_URI, "1"), true);
    waitForResolver();
    ContextProvider.getContext().getContentResolver().notifyChange(CONTENT_URI, null);
    waitForResolver();
    assertTrue(notifyCalled.get());
    notifyCalled.set(false);
    ContextProvider.getContext().getContentResolver().notifyChange(Uri.withAppendedPath(CONTENT_URI, "1"), null);
    waitForResolver();
    assertTrue(notifyCalled.get());
    notifyCalled.set(false);
    ContextProvider.getContext().getContentResolver().notifyChange(Uri.withAppendedPath(CONTENT_URI, "1/directory"), null);
    waitForResolver();
    assertTrue(notifyCalled.get());
}

9. StreamExHeadTailTest#testHeadTailClose()

Project: streamex
Source File: StreamExHeadTailTest.java
View license
@Test
public void testHeadTailClose() {
    AtomicBoolean origClosed = new AtomicBoolean();
    AtomicBoolean internalClosed = new AtomicBoolean();
    AtomicBoolean finalClosed = new AtomicBoolean();
    StreamEx<Integer> res = StreamEx.of(1, 2, 3).onClose(() -> origClosed.set(true)).<Integer>headTail(( head,  stream) -> stream.onClose(() -> internalClosed.set(true)).map( x -> x + head)).onClose(() -> finalClosed.set(true));
    assertEquals(asList(3, 4), res.toList());
    res.close();
    assertTrue(origClosed.get());
    assertTrue(internalClosed.get());
    assertTrue(finalClosed.get());
    res = StreamEx.<Integer>empty().headTail(( head,  tail) -> tail);
    assertEquals(0, res.count());
    res.close();
}

10. GremlinExecutorTest#shouldCallFail()

Project: tinkerpop
Source File: GremlinExecutorTest.java
View license
@Test
public void shouldCallFail() throws Exception {
    final AtomicBoolean timeoutCalled = new AtomicBoolean(false);
    final AtomicBoolean successCalled = new AtomicBoolean(false);
    final AtomicBoolean failureCalled = new AtomicBoolean(false);
    final GremlinExecutor gremlinExecutor = GremlinExecutor.build().afterFailure(( b,  e) -> failureCalled.set(true)).afterSuccess(( b) -> successCalled.set(true)).afterTimeout(( b) -> timeoutCalled.set(true)).create();
    try {
        gremlinExecutor.eval("10/0").get();
        fail();
    } catch (Exception ignored) {
    }
    // need to wait long enough for the callback to register
    Thread.sleep(500);
    assertFalse(timeoutCalled.get());
    assertFalse(successCalled.get());
    assertTrue(failureCalled.get());
    gremlinExecutor.close();
}

11. GremlinExecutorTest#shouldCallSuccess()

Project: tinkerpop
Source File: GremlinExecutorTest.java
View license
@Test
public void shouldCallSuccess() throws Exception {
    final AtomicBoolean timeoutCalled = new AtomicBoolean(false);
    final AtomicBoolean successCalled = new AtomicBoolean(false);
    final AtomicBoolean failureCalled = new AtomicBoolean(false);
    final GremlinExecutor gremlinExecutor = GremlinExecutor.build().afterFailure(( b,  e) -> failureCalled.set(true)).afterSuccess(( b) -> successCalled.set(true)).afterTimeout(( b) -> timeoutCalled.set(true)).create();
    assertEquals(2, gremlinExecutor.eval("1+1").get());
    // need to wait long enough for the callback to register
    Thread.sleep(500);
    assertFalse(timeoutCalled.get());
    assertTrue(successCalled.get());
    assertFalse(failureCalled.get());
    gremlinExecutor.close();
}

12. JMSServerManagerImpl#removeQueueFromBindingRegistry()

View license
@Override
public boolean removeQueueFromBindingRegistry(final String name) throws Exception {
    final AtomicBoolean valueReturn = new AtomicBoolean(false);
    // HORNETQ-911 - make this runAfterActive to prevent WARN messages on shutdown/undeployment when the backup was never activated
    runAfterActive(new WrappedRunnable() {

        @Override
        public String toString() {
            return "removeQueueFromBindings for " + name;
        }

        @Override
        public void runException() throws Exception {
            checkInitialised();
            if (removeFromBindings(queues, queueBindings, name)) {
                storage.deleteDestination(PersistedType.Queue, name);
                valueReturn.set(true);
            }
        }
    });
    return valueReturn.get();
}

13. JMSServerManagerImpl#removeTopicFromBindingRegistry()

View license
/* (non-Javadoc)
   * @see org.apache.activemq.artemis.jms.server.JMSServerManager#removeTopicFromBindings(java.lang.String, java.lang.String)
   */
@Override
public boolean removeTopicFromBindingRegistry(final String name) throws Exception {
    final AtomicBoolean valueReturn = new AtomicBoolean(false);
    // HORNETQ-911 - make this runAfterActive to prevent WARN messages on shutdown/undeployment when the backup was never activated
    runAfterActive(new WrappedRunnable() {

        @Override
        public String toString() {
            return "removeTopicFromBindings for " + name;
        }

        @Override
        public void runException() throws Exception {
            checkInitialised();
            if (removeFromBindings(topics, topicBindings, name)) {
                storage.deleteDestination(PersistedType.Topic, name);
                valueReturn.set(true);
            }
        }
    });
    return valueReturn.get();
}

14. SendHackSelectReceiveUdpPing#run()

View license
private void run() throws IOException {
    receiveChannel = DatagramChannel.open();
    Common.init(receiveChannel);
    receiveChannel.bind(new InetSocketAddress("localhost", Common.PONG_PORT));
    final DatagramChannel sendChannel = DatagramChannel.open();
    Common.init(sendChannel);
    final Selector selector = Selector.open();
    receiveChannel.register(selector, OP_READ, this);
    final NioSelectedKeySet keySet = Common.keySet(selector);
    final AtomicBoolean running = new AtomicBoolean(true);
    SigInt.register(() -> running.set(false));
    while (running.get()) {
        measureRoundTrip(HISTOGRAM, SEND_ADDRESS, buffer, sendChannel, selector, keySet, running);
        HISTOGRAM.reset();
        System.gc();
        LockSupport.parkNanos(1000 * 1000 * 1000);
    }
}

15. ObservablesTest#throwsIllegalStateExceptionForCallOnNonLooperThread()

Project: agera
Source File: ObservablesTest.java
View license
private boolean throwsIllegalStateExceptionForCallOnNonLooperThread(@NonNull final Runnable runnable) {
    final AtomicBoolean gotException = new AtomicBoolean(false);
    final Thread thread = new Thread(new Runnable() {

        @Override
        public void run() {
            try {
                runnable.run();
            } catch (IllegalStateException e) {
                gotException.set(true);
            }
        }
    });
    thread.start();
    try {
        thread.join();
    } catch (InterruptedException ignored) {
    }
    return gotException.get();
}

16. LoadAndDisplayImageTask#waitIfPaused()

View license
/** @return <b>true</b> - if task should be interrupted; <b>false</b> - otherwise */
private boolean waitIfPaused() {
    AtomicBoolean pause = engine.getPause();
    if (pause.get()) {
        synchronized (engine.getPauseLock()) {
            if (pause.get()) {
                L.d(LOG_WAITING_FOR_RESUME, memoryCacheKey);
                try {
                    engine.getPauseLock().wait();
                } catch (InterruptedException e) {
                    L.e(LOG_TASK_INTERRUPTED, memoryCacheKey);
                    return true;
                }
                L.d(LOG_RESUME_AFTER_PAUSE, memoryCacheKey);
            }
        }
    }
    return isTaskNotActual();
}

17. LoadAndDisplayImageTask#waitIfPaused()

View license
/** @return <b>true</b> - if task should be interrupted; <b>false</b> - otherwise */
private boolean waitIfPaused() {
    AtomicBoolean pause = engine.getPause();
    if (pause.get()) {
        synchronized (engine.getPauseLock()) {
            if (pause.get()) {
                L.d(LOG_WAITING_FOR_RESUME, memoryCacheKey);
                try {
                    engine.getPauseLock().wait();
                } catch (InterruptedException e) {
                    L.e(LOG_TASK_INTERRUPTED, memoryCacheKey);
                    return true;
                }
                L.d(LOG_RESUME_AFTER_PAUSE, memoryCacheKey);
            }
        }
    }
    return isTaskNotActual();
}

18. ServiceImplTest#testModuleClassesAreLifecycleManaged()

Project: apollo
Source File: ServiceImplTest.java
View license
@Test
public void testModuleClassesAreLifecycleManaged() throws Exception {
    AtomicBoolean created = new AtomicBoolean(false);
    AtomicBoolean closed = new AtomicBoolean(false);
    ModuleWithLifecycledKeys lifecycleModule = new ModuleWithLifecycledKeys(created, closed);
    Service service = ServiceImpl.builder("test").withModule(lifecycleModule).build();
    try (Service.Instance instance = service.start()) {
        instance.getSignaller().signalShutdown();
        instance.waitForShutdown();
    }
    assertThat(created.get(), is(true));
    assertThat(closed.get(), is(true));
}

19. ServiceImplTest#testResolve()

Project: apollo
Source File: ServiceImplTest.java
View license
@Test
public void testResolve() throws Exception {
    AtomicBoolean created = new AtomicBoolean(false);
    AtomicBoolean closed = new AtomicBoolean(false);
    ModuleWithLifecycledKeys lifecycleModule = new ModuleWithLifecycledKeys(created, closed);
    Service service = ServiceImpl.builder("test").withModule(lifecycleModule).build();
    try (Service.Instance instance = service.start()) {
        ModuleWithLifecycledKeys.Foo foo = instance.resolve(ModuleWithLifecycledKeys.Foo.class);
        assertNotNull(foo);
        instance.getSignaller().signalShutdown();
        instance.waitForShutdown();
    }
}

20. ApolloEnvironmentModuleTest#shouldHandleAppInit()

View license
@Test
public void shouldHandleAppInit() throws Exception {
    final AtomicBoolean init = new AtomicBoolean();
    final AtomicBoolean destroy = new AtomicBoolean();
    try (Service.Instance i = service.build().start()) {
        final ApolloEnvironment environment = ApolloEnvironmentModule.environment(i);
        final RequestHandler handler = environment.initialize( env -> {
            init.set(true);
            env.closer().register(() -> destroy.set(true));
        });
        assertNotNull(handler);
    } catch (IOException e) {
        fail(e.getMessage());
    }
    assertTrue(init.get());
    assertTrue(destroy.get());
}

21. HttpServiceModuleTest#shouldInitAndDestroyApplication()

Project: apollo
Source File: HttpServiceModuleTest.java
View license
@Test
public void shouldInitAndDestroyApplication() throws Exception {
    final AtomicBoolean init = new AtomicBoolean();
    final AtomicBoolean destroy = new AtomicBoolean();
    final App app = new App(init, destroy);
    try (Service.Instance i = service(app).start()) {
        final RequestHandler handler = HttpServiceModule.requestHandler(i);
        assertNotNull(handler);
    } catch (IOException e) {
        fail(e.getMessage());
    }
    assertTrue(init.get());
    assertTrue(destroy.get());
}

22. HttpServiceModuleTest#shouldDestroyApplicationOnExit()

Project: apollo
Source File: HttpServiceModuleTest.java
View license
@Test
public void shouldDestroyApplicationOnExit() throws Exception {
    final AtomicBoolean init = new AtomicBoolean();
    final AtomicBoolean destroy = new AtomicBoolean();
    final App app = new App(init, destroy);
    try (Service.Instance i = service(app).start()) {
        final RequestHandler handler = HttpServiceModule.requestHandler(i);
        assertNotNull(handler);
    // not calling environment.close()
    } catch (IOException e) {
        fail(e.getMessage());
    }
    assertTrue(init.get());
    assertTrue(destroy.get());
}

23. SampleWithMonitoredChannel#main()

View license
public static void main(String[] args) {
    final ChannelStatistics cs = new ChannelStatistics("channel_monitor");
    final EventBus eventBus = new EventBus(new MonitoredChannel(1024, cs));
    eventBus.register(new ListenerSub());
    eventBus.start();
    final AtomicBoolean isEnd = new AtomicBoolean(false);
    new Thread(new Runnable() {

        @Override
        public void run() {
            while (!isEnd.get()) {
                eventBus.publish(new EventA("lee", 10));
            }
        }
    }).start();
    Threads.sleep(1000);
    isEnd.set(true);
    eventBus.stop();
    System.out.println("===End====" + cs);
//===End====CHANNEL:channel_monitor{channel.event.put.success=239598, channel.current.size=0, channel.capacity=1024, channel.event.take.attempt=239625, channel.event.take.success=239625, channel.event.put.attempt=541960}
//????????????????????????
}

24. LaunchStatusHandler#handleStatus()

Project: bndtools
Source File: LaunchStatusHandler.java
View license
public Boolean handleStatus(final IStatus status, Object source) throws CoreException {
    if (status.isOK())
        return true;
    final AtomicBoolean result = new AtomicBoolean();
    Runnable uitask = new Runnable() {

        public void run() {
            LaunchStatusDialog dialog = new LaunchStatusDialog(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(), status);
            int response = dialog.open();
            result.set(response == Window.OK);
        }
    };
    Display display = PlatformUI.getWorkbench().getDisplay();
    if (display.getThread() == Thread.currentThread())
        uitask.run();
    else
        display.syncExec(uitask);
    return result.get();
}

25. ListeningSemaphoreTest#doubleAcquireWithEnoughPermits()

Project: buck
Source File: ListeningSemaphoreTest.java
View license
@Test
public void doubleAcquireWithEnoughPermits() {
    ListeningSemaphore semaphore = new ListeningSemaphore(2);
    assertThat(semaphore.availablePermits(), Matchers.equalTo(2));
    assertThat(semaphore.getQueueLength(), Matchers.equalTo(0));
    // Acquire a single permit and verify it goes through.
    AtomicBoolean first = acquire(semaphore, 1);
    assertThat(semaphore.availablePermits(), Matchers.equalTo(1));
    assertThat(semaphore.getQueueLength(), Matchers.equalTo(0));
    assertTrue(first.get());
    // Acquire a single permit and verify it goes through.
    AtomicBoolean second = acquire(semaphore, 1);
    assertThat(semaphore.availablePermits(), Matchers.equalTo(0));
    assertThat(semaphore.getQueueLength(), Matchers.equalTo(0));
    assertTrue(second.get());
}

26. ListeningSemaphoreTest#blockedAcquire()

Project: buck
Source File: ListeningSemaphoreTest.java
View license
@Test
public void blockedAcquire() {
    ListeningSemaphore semaphore = new ListeningSemaphore(1);
    assertThat(semaphore.availablePermits(), Matchers.equalTo(1));
    assertThat(semaphore.getQueueLength(), Matchers.equalTo(0));
    // Verify that a simple acquire works.
    AtomicBoolean first = acquire(semaphore, 1);
    assertThat(semaphore.availablePermits(), Matchers.equalTo(0));
    assertThat(semaphore.getQueueLength(), Matchers.equalTo(0));
    assertTrue(first.get());
    // Verify that a subsequent acquire blocks.
    AtomicBoolean second = acquire(semaphore, 1);
    assertThat(semaphore.availablePermits(), Matchers.equalTo(0));
    assertFalse(second.get());
    assertThat(semaphore.getQueueLength(), Matchers.equalTo(1));
    // Release the semaphore from the first acquisition and verify that the second
    // acquire was unblocked.
    semaphore.release(1);
    assertTrue(second.get());
    assertThat(semaphore.availablePermits(), Matchers.equalTo(0));
    assertThat(semaphore.getQueueLength(), Matchers.equalTo(0));
}

27. ListeningSemaphoreTest#weightedBlockedAcquire()

Project: buck
Source File: ListeningSemaphoreTest.java
View license
@Test
public void weightedBlockedAcquire() {
    ListeningSemaphore semaphore = new ListeningSemaphore(2);
    assertThat(semaphore.availablePermits(), Matchers.equalTo(2));
    assertThat(semaphore.getQueueLength(), Matchers.equalTo(0));
    // Verify that a simple acquire works.
    AtomicBoolean first = acquire(semaphore, 1);
    assertThat(semaphore.availablePermits(), Matchers.equalTo(1));
    assertThat(semaphore.getQueueLength(), Matchers.equalTo(0));
    assertTrue(first.get());
    // Verify that a subsequent acquire blocks.
    AtomicBoolean second = acquire(semaphore, 2);
    assertThat(semaphore.availablePermits(), Matchers.equalTo(1));
    assertFalse(second.get());
    assertThat(semaphore.getQueueLength(), Matchers.equalTo(1));
    // Release the semaphore from the first acquisition and verify that the second
    // acquire was unblocked.
    semaphore.release(1);
    assertTrue(second.get());
    assertThat(semaphore.availablePermits(), Matchers.equalTo(0));
    assertThat(semaphore.getQueueLength(), Matchers.equalTo(0));
}

28. ListeningSemaphoreTest#fastFairness()

Project: buck
Source File: ListeningSemaphoreTest.java
View license
@Test
public void fastFairness() {
    ListeningSemaphore semaphore = new ListeningSemaphore(1, ListeningSemaphore.Cap.HARD, ListeningSemaphore.Fairness.FAST);
    assertThat(semaphore.availablePermits(), Matchers.equalTo(1));
    assertThat(semaphore.getQueueLength(), Matchers.equalTo(0));
    // Try to acquire more permits than we have, which should block.
    AtomicBoolean first = acquire(semaphore, 2);
    assertThat(semaphore.availablePermits(), Matchers.equalTo(1));
    assertThat(semaphore.getQueueLength(), Matchers.equalTo(1));
    assertFalse(first.get());
    // Acquire a single permit and verify it goes through.
    AtomicBoolean second = acquire(semaphore, 1);
    assertThat(semaphore.availablePermits(), Matchers.equalTo(0));
    assertThat(semaphore.getQueueLength(), Matchers.equalTo(1));
    assertTrue(second.get());
}

29. SchedulerTest#testScheduleAndRepeat()

Project: BungeeCord
Source File: SchedulerTest.java
View license
@Test
public void testScheduleAndRepeat() throws InterruptedException {
    TaskScheduler scheduler = new BungeeScheduler();
    AtomicBoolean b = new AtomicBoolean();
    setup(scheduler, b);
    Thread.sleep(250);
    Assert.assertTrue(b.get());
    b.set(false);
    Thread.sleep(250);
    Assert.assertTrue(b.get());
}

30. AsyncCallbackAdapterTest#testCallback()

View license
@Test
public void testCallback() {
    final AtomicBoolean onSuccess = new AtomicBoolean(false);
    final AtomicBoolean onFailure = new AtomicBoolean(false);
    final AsyncCallbackAdapter<Object> callback = new AsyncCallbackAdapter<Object>() {

        @Override
        public void onSuccess(final Object result) {
            super.onSuccess(result);
            onSuccess.set(true);
        }

        @Override
        public void onFailure(final Throwable caught) {
            super.onFailure(caught);
            onFailure.set(true);
        }
    };
    callback.onSuccess(null);
    callback.onFailure(null);
    Assert.assertTrue(onSuccess.get());
    Assert.assertTrue(onFailure.get());
}

31. FutureCallbackAdapterTest#testCallback()

View license
@Test
public void testCallback() {
    final AtomicBoolean onSuccess = new AtomicBoolean(false);
    final AtomicBoolean onFailure = new AtomicBoolean(false);
    final FutureCallbackAdapter<Object> callback = new FutureCallbackAdapter<Object>() {

        @Override
        public void onSuccess(final Object result) {
            super.onSuccess(result);
            onSuccess.set(true);
        }

        @Override
        public void onFailure(final Throwable caught) {
            super.onFailure(caught);
            onFailure.set(true);
        }
    };
    callback.onSuccess(null);
    callback.onFailure(null);
    Assert.assertTrue(onSuccess.get());
    Assert.assertTrue(onFailure.get());
}

32. AsyncLoadingCacheTest#refresh()

Project: caffeine
Source File: AsyncLoadingCacheTest.java
View license
/* ---------------- refresh -------------- */
@Test(dataProvider = "caches")
@CacheSpec(implementation = Implementation.Caffeine, population = Population.EMPTY, executor = CacheExecutor.THREADED, compute = Compute.ASYNC, values = ReferenceType.STRONG)
public void refresh(CacheContext context) {
    AtomicBoolean done = new AtomicBoolean();
    AsyncLoadingCache<Integer, Integer> cache = context.buildAsync( key -> {
        await().untilTrue(done);
        return -key;
    });
    Integer key = 1;
    cache.synchronous().put(key, key);
    CompletableFuture<Integer> original = cache.get(key);
    for (int i = 0; i < 10; i++) {
        context.ticker().advance(1, TimeUnit.SECONDS);
        cache.synchronous().refresh(key);
        CompletableFuture<Integer> next = cache.get(key);
        assertThat(next, is(sameInstance(original)));
    }
    done.set(true);
    await().until(() -> cache.synchronous().getIfPresent(key), is(-key));
}

33. LoadingCacheTest#refresh_invalidate()

Project: caffeine
Source File: LoadingCacheTest.java
View license
@Test(dataProvider = "caches")
@CacheSpec(population = Population.EMPTY, executor = CacheExecutor.THREADED, removalListener = Listener.CONSUMING)
public void refresh_invalidate(CacheContext context) {
    AtomicBoolean refresh = new AtomicBoolean();
    Integer key = context.absentKey();
    Integer original = 1;
    Integer refreshed = 2;
    LoadingCache<Integer, Integer> cache = context.build( k -> {
        await().untilTrue(refresh);
        return refreshed;
    });
    cache.put(key, original);
    cache.refresh(key);
    cache.invalidate(key);
    refresh.set(true);
    await().until(() -> cache.getIfPresent(key), is(refreshed));
    await().until(() -> cache, hasRemovalNotifications(context, 1, RemovalCause.EXPLICIT));
    await().until(() -> context, both(hasLoadSuccessCount(1)).and(hasLoadFailureCount(0)));
}

34. RefreshAfterWriteTest#get_sameFuture()

Project: caffeine
Source File: RefreshAfterWriteTest.java
View license
@Test(dataProvider = "caches")
@CacheSpec(implementation = Implementation.Caffeine, population = Population.EMPTY, refreshAfterWrite = Expire.ONE_MINUTE, executor = CacheExecutor.THREADED, compute = Compute.ASYNC, values = ReferenceType.STRONG)
public void get_sameFuture(CacheContext context) {
    AtomicBoolean done = new AtomicBoolean();
    AsyncLoadingCache<Integer, Integer> cache = context.buildAsync( key -> {
        await().untilTrue(done);
        return -key;
    });
    Integer key = 1;
    cache.synchronous().put(key, key);
    CompletableFuture<Integer> original = cache.get(key);
    for (int i = 0; i < 10; i++) {
        context.ticker().advance(1, TimeUnit.MINUTES);
        CompletableFuture<Integer> next = cache.get(key);
        assertThat(next, is(sameInstance(original)));
    }
    done.set(true);
    await().until(() -> cache.synchronous().getIfPresent(key), is(-key));
}

35. RefreshAfterWriteTest#invalidate()

Project: caffeine
Source File: RefreshAfterWriteTest.java
View license
/* ---------------- invalidate -------------- */
@Test(dataProvider = "caches")
@CacheSpec(population = Population.EMPTY, refreshAfterWrite = Expire.ONE_MINUTE, executor = CacheExecutor.THREADED, removalListener = Listener.CONSUMING)
public void invalidate(CacheContext context) {
    AtomicBoolean refresh = new AtomicBoolean();
    Integer key = context.absentKey();
    Integer original = 1;
    Integer refreshed = 2;
    LoadingCache<Integer, Integer> cache = context.build( k -> {
        await().untilTrue(refresh);
        return refreshed;
    });
    cache.put(key, original);
    context.ticker().advance(2, TimeUnit.MINUTES);
    assertThat(cache.getIfPresent(key), is(original));
    cache.invalidate(key);
    refresh.set(true);
    await().until(() -> cache.getIfPresent(key), is(refreshed));
    assertThat(cache, hasRemovalNotifications(context, 1, RemovalCause.EXPLICIT));
    assertThat(context, both(hasLoadSuccessCount(1)).and(hasLoadFailureCount(0)));
}

36. MapReduceRunnerTestBase#waitForCompletion()

Project: cdap
Source File: MapReduceRunnerTestBase.java
View license
private boolean waitForCompletion(ProgramController controller) throws InterruptedException {
    final AtomicBoolean success = new AtomicBoolean(false);
    final CountDownLatch completion = new CountDownLatch(1);
    controller.addListener(new AbstractListener() {

        @Override
        public void completed() {
            success.set(true);
            completion.countDown();
        }

        @Override
        public void error(Throwable cause) {
            completion.countDown();
        }
    }, Threads.SAME_THREAD_EXECUTOR);
    // MR tests can run for long time.
    completion.await(5, TimeUnit.MINUTES);
    return success.get();
}

37. TableConcurrentTest#testConcurrentCreate()

Project: cdap
Source File: TableConcurrentTest.java
View license
/**
   * tests that creating a table concurrently from two different clients does not fail.
   */
// table create wait time is 5 sec
@Test(timeout = 20000)
public void testConcurrentCreate() throws Exception {
    AtomicBoolean success1 = new AtomicBoolean(false);
    AtomicBoolean success2 = new AtomicBoolean(false);
    // start two threads both attempting to create the same table
    Thread t1 = new CreateThread(success1);
    Thread t2 = new CreateThread(success2);
    t1.start();
    t2.start();
    t1.join();
    t2.join();
    // make sure both threads report success
    Assert.assertTrue("First thread failed. ", success1.get());
    Assert.assertTrue("Second thread failed. ", success2.get());
    // perform a read - if the table was not opened successfully this will fail
    getTable(CONTEXT1, "conccreate").get(new byte[] { 'a' }, new byte[][] { { 'b' } });
}

38. ChronicleNfsVirtualFileSystem#move()

View license
@Override
public boolean move(@NotNull Inode parent, String oldName, Inode dest, String newName) throws IOException {
    final Object d = ChronicleNfsFileHandleLookup.reverseLookup(parent.getFileId());
    if (!(d instanceof Asset))
        throw new IOException("Unsupported: parent type=" + d);
    final Asset asset = (Asset) d;
    if (asset.getChild(oldName) != null)
        throw new IOException("Unsupported: can not a directory move");
    final MapView mapView = asset.acquireView(MapView.class);
    final AtomicBoolean wasReplaced = new AtomicBoolean();
    // we use computeIfAbsent as it can be treated atomically in the future
    //noinspection unchecked
    mapView.computeIfAbsent(newName,  k -> {
        Object oldValue = mapView.getAndRemove(oldName);
        wasReplaced.set(true);
        return oldValue;
    });
    return wasReplaced.get();
}

39. ClientSessionStateTest#testSessionStateChange()

Project: copycat
Source File: ClientSessionStateTest.java
View license
/**
   * Tests session state change callbacks.
   */
public void testSessionStateChange() {
    ClientSessionState state = new ClientSessionState(UUID.randomUUID());
    AtomicBoolean changed = new AtomicBoolean();
    AtomicReference<Session.State> change = new AtomicReference<>();
    Listener<Session.State> listener = state.onStateChange( s -> {
        changed.set(true);
        change.set(s);
    });
    assertEquals(state.getState(), Session.State.CLOSED);
    state.setState(Session.State.CLOSED);
    assertFalse(changed.get());
    state.setState(Session.State.OPEN);
    assertTrue(changed.get());
    assertEquals(change.get(), Session.State.OPEN);
    changed.set(false);
    listener.close();
    state.setState(Session.State.EXPIRED);
    assertFalse(changed.get());
}

40. DrawerActions#checkDrawer()

Project: double-espresso
Source File: DrawerActions.java
View license
/**
   * Returns true if the given matcher matches the drawer.
   */
private static boolean checkDrawer(int drawerLayoutId, final Matcher<View> matcher) {
    final AtomicBoolean matches = new AtomicBoolean(false);
    onView(withId(drawerLayoutId)).perform(new ViewAction() {

        @Override
        public Matcher<View> getConstraints() {
            return isAssignableFrom(DrawerLayout.class);
        }

        @Override
        public String getDescription() {
            return "check drawer";
        }

        @Override
        public void perform(UiController uiController, View view) {
            matches.set(matcher.matches(view));
        }
    });
    return matches.get();
}

41. TestMarshallingUtilsTest#testCompareAtomicPrimitives()

View license
@Test
@Ignore
public void testCompareAtomicPrimitives() {
    AtomicInteger objA = new AtomicInteger(-1);
    AtomicInteger objB = new AtomicInteger(-1);
    int a = objA.get();
    int b = objB.get();
    assertFalse("objs?", objA.equals(objB));
    assertTrue("ints?", a == b);
    assertTrue("compare a?", CompareViaReflectionUtil.compareAtomicPrimitives(objA, objB));
    AtomicBoolean objC = new AtomicBoolean(false);
    AtomicBoolean objD = new AtomicBoolean(false);
    boolean c = objC.get();
    boolean d = objD.get();
    assertFalse("objs?", objC.equals(objD));
    assertTrue("bools?", c == d);
    assertTrue("compare c?", CompareViaReflectionUtil.compareAtomicPrimitives(objC, objD));
}

42. FileSystemUtils#hasExtensions()

Project: elassandra
Source File: FileSystemUtils.java
View license
/**
     * Returns <code>true</code> iff a file under the given root has one of the given extensions. This method
     * will travers directories recursively and will terminate once any of the extensions was found. This
     * methods will not follow any links.
     *
     * @param root the root directory to travers. Must be a directory
     * @param extensions the file extensions to look for
     * @return <code>true</code> iff a file under the given root has one of the given extensions, otherwise <code>false</code>
     * @throws IOException if an IOException occurs or if the given root path is not a directory.
     */
public static boolean hasExtensions(Path root, final String... extensions) throws IOException {
    final AtomicBoolean retVal = new AtomicBoolean(false);
    Files.walkFileTree(root, new SimpleFileVisitor<Path>() {

        @Override
        public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
            for (String extension : extensions) {
                if (file.getFileName().toString().endsWith(extension)) {
                    retVal.set(true);
                    return FileVisitResult.TERMINATE;
                }
            }
            return super.visitFile(file, attrs);
        }
    });
    return retVal.get();
}

43. RepositoryTest#subscribe()

Project: es4j
Source File: RepositoryTest.java
View license
@Test
@SneakyThrows
public void subscribe() {
    final AtomicBoolean gotEvent = new AtomicBoolean();
    final AtomicBoolean gotCommand = new AtomicBoolean();
    repository.addEntitySubscriber(new ClassEntitySubscriber<TestEvent>(TestEvent.class) {

        @Override
        public void onEntity(EntityHandle<TestEvent> entity) {
            gotEvent.set(journal.get(entity.uuid()).isPresent());
        }
    });
    repository.addEntitySubscriber(new ClassEntitySubscriber<RepositoryTestCommand>(RepositoryTestCommand.class) {

        @Override
        public void onEntity(EntityHandle<RepositoryTestCommand> entity) {
            gotCommand.set(journal.get(entity.uuid()).isPresent());
        }
    });
    repository.publish(RepositoryTestCommand.builder().build()).get();
    assertTrue(gotEvent.get());
    assertTrue(gotCommand.get());
}

44. ContextTest#childContextListenerNotifiedAfterParentListener()

Project: grpc-java
Source File: ContextTest.java
View license
@Test
public void childContextListenerNotifiedAfterParentListener() {
    Context.CancellableContext parent = Context.current().withCancellation();
    Context child = parent.withValue(COLOR, "red");
    final AtomicBoolean childAfterParent = new AtomicBoolean();
    final AtomicBoolean parentCalled = new AtomicBoolean();
    child.addListener(new Context.CancellationListener() {

        @Override
        public void cancelled(Context context) {
            if (parentCalled.get()) {
                childAfterParent.set(true);
            }
        }
    }, MoreExecutors.directExecutor());
    parent.addListener(new Context.CancellationListener() {

        @Override
        public void cancelled(Context context) {
            parentCalled.set(true);
        }
    }, MoreExecutors.directExecutor());
    parent.cancel(null);
    assertTrue(parentCalled.get());
    assertTrue(childAfterParent.get());
}

45. MoreExecutorsTest#testShutdownAndAwaitTermination_interruptedInternal()

Project: guava
Source File: MoreExecutorsTest.java
View license
public void testShutdownAndAwaitTermination_interruptedInternal() throws Exception {
    final ExecutorService service = mock(ExecutorService.class);
    when(service.awaitTermination(HALF_SECOND_NANOS, NANOSECONDS)).thenThrow(new InterruptedException());
    final AtomicBoolean terminated = new AtomicBoolean();
    // we need to keep this in a flag because t.isInterrupted() returns false after t.join()
    final AtomicBoolean interrupted = new AtomicBoolean();
    // we need to use another thread because it will be interrupted and thus using
    // the current one, owned by JUnit, would make the test fail
    Thread thread = new Thread(new Runnable() {

        @Override
        public void run() {
            terminated.set(shutdownAndAwaitTermination(service, 1L, SECONDS));
            interrupted.set(Thread.currentThread().isInterrupted());
        }
    });
    thread.start();
    thread.join();
    verify(service).shutdown();
    verify(service).awaitTermination(HALF_SECOND_NANOS, NANOSECONDS);
    verify(service).shutdownNow();
    assertTrue(interrupted.get());
    assertFalse(terminated.get());
}

46. SupplementalMonitorTest#verifyOccupiedMethodsInAnotherThread()

Project: guava
Source File: SupplementalMonitorTest.java
View license
private static void verifyOccupiedMethodsInAnotherThread(final Monitor monitor, boolean expectedIsOccupied, boolean expectedIsOccupiedByCurrentThread, int expectedOccupiedDepth) {
    final AtomicBoolean actualIsOccupied = new AtomicBoolean();
    final AtomicBoolean actualIsOccupiedByCurrentThread = new AtomicBoolean();
    final AtomicInteger actualOccupiedDepth = new AtomicInteger();
    final AtomicReference<Throwable> thrown = new AtomicReference<Throwable>();
    joinUninterruptibly(startThread(new Runnable() {

        @Override
        public void run() {
            try {
                actualIsOccupied.set(monitor.isOccupied());
                actualIsOccupiedByCurrentThread.set(monitor.isOccupiedByCurrentThread());
                actualOccupiedDepth.set(monitor.getOccupiedDepth());
            } catch (Throwable t) {
                thrown.set(t);
            }
        }
    }));
    assertNull(thrown.get());
    assertEquals(expectedIsOccupied, actualIsOccupied.get());
    assertEquals(expectedIsOccupiedByCurrentThread, actualIsOccupiedByCurrentThread.get());
    assertEquals(expectedOccupiedDepth, actualOccupiedDepth.get());
}

47. TaskList#processTasks()

Project: HMCL
Source File: TaskList.java
View license
private boolean processTasks(Collection<? extends Task> c) {
    if (c == null || c.isEmpty())
        return true;
    this.totTask += c.size();
    AtomicBoolean bool = new AtomicBoolean(true);
    CountDownLatch counter = new CountDownLatch(c.size());
    for (Task t2 : c) {
        if (t2 == null)
            continue;
        t2.setParallelExecuting(true);
        Invoker thread = new Invoker(t2, counter, bool);
        invokers.add(thread);
        if (!EXECUTOR_SERVICE.isShutdown() && !EXECUTOR_SERVICE.isTerminated())
            futures.put(thread, EXECUTOR_SERVICE.submit(thread));
    }
    try {
        counter.await();
    } catch (InterruptedException ignore) {
    }
    return bool.get();
}

48. DataStoreUtil#importJobDataParallel()

Project: hydra
Source File: DataStoreUtil.java
View license
private static void importJobDataParallel(List<String> jobIds, SpawnDataStore sourceDataStore, SpawnDataStore targetDataStore, boolean checkAllWrites) throws Exception {
    ExecutorService executorService = new ThreadPoolExecutor(numCutoverThreads, numCutoverThreads, 60, TimeUnit.SECONDS, new LinkedBlockingQueue<>());
    AtomicBoolean gotFailures = new AtomicBoolean(false);
    int partitionSize = Math.max((int) Math.ceil((double) jobIds.size() / numCutoverThreads), 1);
    for (List<String> partition : Lists.partition(jobIds, partitionSize)) {
        executorService.submit(new CutoverWorker(sourceDataStore, targetDataStore, gotFailures, partition, checkAllWrites));
    }
    executorService.shutdown();
    executorService.awaitTermination(cutoverTimeoutMinutes, TimeUnit.MINUTES);
    if (gotFailures.get()) {
        throw new RuntimeException("A cutover worker has failed; see log for details");
    }
}

49. IgniteAtomicLongChangingTopologySelfTest#testQueueCreateNodesJoin()

View license
/**
     * @throws Exception If failed.
     */
public void testQueueCreateNodesJoin() throws Exception {
    CountDownLatch startLatch = new CountDownLatch(GRID_CNT);
    final AtomicBoolean run = new AtomicBoolean(true);
    Collection<IgniteInternalFuture<?>> futs = new ArrayList<>();
    for (int i = 0; i < GRID_CNT; i++) futs.add(startNodeAndCreaterThread(i, startLatch, run));
    startLatch.await();
    info("All nodes started.");
    Thread.sleep(10_000);
    run.set(false);
    for (IgniteInternalFuture<?> fut : futs) fut.get();
    info("Increments: " + queue.size());
    assert !queue.isEmpty();
}

50. GridThreadPriorityTest#main()

Project: ignite
Source File: GridThreadPriorityTest.java
View license
/**
     * @param args Args.
     * @throws Exception If failed.
     */
public static void main(String[] args) throws Exception {
    AtomicBoolean finish = new AtomicBoolean();
    for (int j = 0; j < Runtime.getRuntime().availableProcessors(); j++) {
        for (int i = Thread.MIN_PRIORITY; i <= Thread.MAX_PRIORITY; i++) new TestThread(finish, i).start();
    }
    Thread.sleep(30 * 1000);
    finish.set(true);
}

51. GridSessionCancelSiblingsFromFutureSelfTest#testMultiThreaded()

View license
/**
     * @throws Exception if failed
     */
public void testMultiThreaded() throws Exception {
    refreshInitialData();
    final GridThreadSerialNumber sNum = new GridThreadSerialNumber();
    final AtomicBoolean failed = new AtomicBoolean(false);
    GridTestUtils.runMultiThreaded(new Runnable() {

        @Override
        public void run() {
            int num = sNum.get();
            try {
                checkTask(num);
            } catch (Throwable e) {
                error("Failed to execute task.", e);
                failed.set(true);
            }
        }
    }, EXEC_COUNT, "grid-session-test");
    if (failed.get())
        fail();
}

52. GridSessionCancelSiblingsFromJobSelfTest#testMultiThreaded()

View license
/**
     * @throws Exception If failed.
     */
public void testMultiThreaded() throws Exception {
    refreshInitialData();
    final GridThreadSerialNumber sNum = new GridThreadSerialNumber();
    final AtomicBoolean failed = new AtomicBoolean(false);
    GridTestUtils.runMultiThreaded(new Runnable() {

        @Override
        public void run() {
            int num = sNum.get();
            try {
                checkTask(num);
            } catch (Throwable e) {
                error("Failed to execute task.", e);
                failed.set(true);
            }
        }
    }, EXEC_COUNT, "grid-session-test");
    if (failed.get())
        fail();
}

53. GridSessionCancelSiblingsFromTaskSelfTest#testMultiThreaded()

View license
/**
     * @throws Exception If failed.
     */
public void testMultiThreaded() throws Exception {
    refreshInitialData();
    final GridThreadSerialNumber sNum = new GridThreadSerialNumber();
    final AtomicBoolean failed = new AtomicBoolean(false);
    GridTestUtils.runMultiThreaded(new Runnable() {

        @Override
        public void run() {
            int num = sNum.get();
            try {
                checkTask(num);
            } catch (Throwable e) {
                error("Failed to execute task.", e);
                failed.set(true);
            }
        }
    }, EXEC_COUNT, "grid-session-test");
    if (failed.get())
        fail();
}

54. GridSessionSetFutureAttributeSelfTest#testMultiThreaded()

View license
/**
     * @throws Exception if failed.
     */
public void testMultiThreaded() throws Exception {
    refreshInitialData();
    final GridThreadSerialNumber sNum = new GridThreadSerialNumber();
    final AtomicBoolean failed = new AtomicBoolean(false);
    GridTestUtils.runMultiThreaded(new Runnable() {

        @Override
        public void run() {
            int num = sNum.get();
            try {
                checkTask(num);
            } catch (Throwable e) {
                error("Failed to execute task.", e);
                failed.set(true);
            }
        }
    }, EXEC_COUNT, "grid-session-test");
    if (failed.get())
        fail();
}

55. GridSessionSetJobAttributeSelfTest#testMultiThreaded()

View license
/**
     * @throws Exception if failed.
     */
public void testMultiThreaded() throws Exception {
    final GridThreadSerialNumber sNum = new GridThreadSerialNumber();
    final AtomicBoolean failed = new AtomicBoolean(false);
    GridTestUtils.runMultiThreaded(new Runnable() {

        @Override
        public void run() {
            int num = sNum.get();
            try {
                checkTask(num);
            } catch (Throwable e) {
                error("Failed to execute task.", e);
                failed.set(true);
            }
        }
    }, EXEC_COUNT, "grid-session-test");
    if (failed.get())
        fail();
}

56. GridLoadTestUtils#runMultithreadedInLoop()

Project: ignite
Source File: GridLoadTestUtils.java
View license
/**
     * Runs a given callable in loop in multiple threads for specified period of time.
     *
     * @param c Callable to run.
     * @param threadCnt Thread count.
     * @param dur Run duration in milliseconds.
     */
public static void runMultithreadedInLoop(final Callable<?> c, int threadCnt, long dur) {
    ExecutorService pool = Executors.newFixedThreadPool(threadCnt);
    final AtomicBoolean finish = new AtomicBoolean();
    for (int i = 0; i < threadCnt; i++) pool.submit(new Callable<Object>() {

        @Nullable
        @Override
        public Object call() throws Exception {
            while (!finish.get()) c.call();
            return null;
        }
    });
    try {
        Thread.sleep(dur);
    } catch (InterruptedException ignored) {
    }
    finish.set(true);
    pool.shutdown();
}

57. ServicesTest#testCompletion()

Project: incubator-twill
Source File: ServicesTest.java
View license
@Test
public void testCompletion() throws ExecutionException, InterruptedException {
    Service service = new DummyService("s1", new AtomicBoolean());
    ListenableFuture<Service.State> completion = Services.getCompletionFuture(service);
    service.start();
    service.stop();
    completion.get();
    AtomicBoolean transiting = new AtomicBoolean();
    service = new DummyService("s2", transiting);
    completion = Services.getCompletionFuture(service);
    service.startAndWait();
    transiting.set(true);
    service.stop();
    try {
        completion.get();
        Assert.assertTrue(false);
    } catch (ExecutionException e) {
    }
}

58. GitBranchUiHandlerImpl#notifyErrorWithRollbackProposal()

View license
@Override
public boolean notifyErrorWithRollbackProposal(@NotNull final String title, @NotNull final String message, @NotNull final String rollbackProposal) {
    final AtomicBoolean ok = new AtomicBoolean();
    UIUtil.invokeAndWaitIfNeeded(new Runnable() {

        @Override
        public void run() {
            StringBuilder description = new StringBuilder();
            if (!StringUtil.isEmptyOrSpaces(message)) {
                description.append(message).append("<br/>");
            }
            description.append(rollbackProposal);
            ok.set(Messages.YES == DialogManager.showOkCancelDialog(myProject, XmlStringUtil.wrapInHtml(description), title, "Rollback", "Don't rollback", Messages.getErrorIcon()));
        }
    });
    return ok.get();
}

59. GitBranchUiHandlerImpl#showUnmergedFilesMessageWithRollback()

View license
@Override
public boolean showUnmergedFilesMessageWithRollback(@NotNull final String operationName, @NotNull final String rollbackProposal) {
    final AtomicBoolean ok = new AtomicBoolean();
    UIUtil.invokeAndWaitIfNeeded(new Runnable() {

        @Override
        public void run() {
            String description = String.format("<html>You have to resolve all merge conflicts before %s.<br/>%s</html>", operationName, rollbackProposal);
            // suppressing: this message looks ugly if capitalized by words
            //noinspection DialogTitleCapitalization
            ok.set(Messages.YES == DialogManager.showOkCancelDialog(myProject, description, unmergedFilesErrorTitle(operationName), "Rollback", "Don't rollback", Messages.getErrorIcon()));
        }
    });
    return ok.get();
}

60. GitCheckoutOperation#smartCheckout()

View license
// stash - checkout - unstash
private boolean smartCheckout(@NotNull final List<GitRepository> repositories, @NotNull final String reference, @Nullable final String newBranch, @NotNull ProgressIndicator indicator) {
    final AtomicBoolean result = new AtomicBoolean();
    GitPreservingProcess preservingProcess = new GitPreservingProcess(myProject, myGit, GitUtil.getRootsFromRepositories(repositories), "checkout", reference, GitVcsSettings.UpdateChangesPolicy.STASH, indicator, new Runnable() {

        @Override
        public void run() {
            result.set(checkoutOrNotify(repositories, reference, newBranch, false));
        }
    });
    preservingProcess.execute();
    return result.get();
}

61. GitMergeOperation#doSmartMerge()

View license
private boolean doSmartMerge(@NotNull final Collection<GitRepository> repositories) {
    final AtomicBoolean success = new AtomicBoolean();
    myPreservingProcess = new GitPreservingProcess(myProject, myGit, GitUtil.getRootsFromRepositories(repositories), "merge", myBranchToMerge, GitVcsSettings.UpdateChangesPolicy.STASH, getIndicator(), new Runnable() {

        @Override
        public void run() {
            success.set(doMerge(repositories));
        }
    });
    myPreservingProcess.execute(new Computable<Boolean>() {

        @Override
        public Boolean compute() {
            return myConflictedRepositories.isEmpty();
        }
    });
    return success.get();
}

62. GitSSHGUIHandler#verifyServerHostKey()

View license
public boolean verifyServerHostKey(final String hostname, final int port, final String serverHostKeyAlgorithm, final String fingerprint, final boolean isNew) {
    final String message;
    if (isNew) {
        message = GitBundle.message("ssh.new.host.key", hostname, port, fingerprint, serverHostKeyAlgorithm);
    } else {
        message = GitBundle.message("ssh.changed.host.key", hostname, port, fingerprint, serverHostKeyAlgorithm);
    }
    final AtomicBoolean rc = new AtomicBoolean();
    ApplicationManager.getApplication().invokeAndWait(new Runnable() {

        public void run() {
            rc.set(Messages.YES == Messages.showYesNoDialog(myProject, message, GitBundle.getString("ssh.confirm.key.titile"), null));
        }
    }, ModalityState.any());
    return rc.get();
}

63. Entities#findEntityRecursively()

Project: JALSE
Source File: Entities.java
View license
/**
     * Walks through the entity tree looking for an entity.
     *
     * @param container
     *            Entity container.
     * @param id
     *            Entity ID to look for.
     * @return Whether the entity was found.
     *
     * @see #walkEntityTree(EntityContainer, EntityVisitor)
     */
public static boolean findEntityRecursively(final EntityContainer container, final UUID id) {
    final AtomicBoolean found = new AtomicBoolean();
    walkEntityTree(container,  e -> {
        if (id.equals(e.getID())) {
            found.set(true);
            return EntityVisitResult.EXIT;
        } else {
            return EntityVisitResult.CONTINUE;
        }
    });
    return found.get();
}

64. DiffNode#hasChanges()

Project: java-object-diff
Source File: DiffNode.java
View license
public boolean hasChanges() {
    if (isAdded() || isChanged() || isRemoved()) {
        return true;
    }
    final AtomicBoolean result = new AtomicBoolean(false);
    visitChildren(new Visitor() {

        public void node(final DiffNode node, final Visit visit) {
            if (node.hasChanges()) {
                result.set(true);
                visit.stop();
            }
        }
    });
    return result.get();
}

65. SEQUENCER2#deliver()

Project: JGroups
Source File: SEQUENCER2.java
View license
protected void deliver(Message msg, SequencerHeader hdr) {
    Address sender = msg.getSrc();
    if (sender == null) {
        if (log.isErrorEnabled())
            log.error(local_addr + ": sender is null, cannot deliver " + "::" + hdr.getSeqno());
        return;
    }
    final Table<Message> win = received_msgs;
    win.add(hdr.seqno, msg);
    final AtomicBoolean processing = win.getProcessing();
    if (processing.compareAndSet(false, true))
        removeAndDeliver(processing, win, sender);
}

66. SeqTest#testCloseStreamConcat()

Project: jOOL
Source File: SeqTest.java
View license
@Test
public void testCloseStreamConcat() {
    AtomicBoolean closed1 = new AtomicBoolean();
    AtomicBoolean closed2 = new AtomicBoolean();
    Stream s1 = Stream.of(1, 2).onClose(() -> closed1.set(true));
    Stream s2 = Stream.of(3).onClose(() -> closed2.set(true));
    try (Stream s3 = Stream.concat(s1, s2)) {
        s3.collect(Collectors.toList());
    }
    assertTrue(closed1.get());
    assertTrue(closed2.get());
}

67. Collection8Test#testForEachConcurrentStressTest()

Project: mapdb
Source File: Collection8Test.java
View license
public void testForEachConcurrentStressTest() throws Throwable {
    if (!impl.isConcurrent())
        return;
    final Collection c = impl.emptyCollection();
    final long testDurationMillis = SHORT_DELAY_MS;
    final AtomicBoolean done = new AtomicBoolean(false);
    final Object elt = impl.makeElement(1);
    ExecutorService pool = Executors.newCachedThreadPool();
    Runnable checkElt = () -> {
        while (!done.get()) c.stream().forEach(( x) -> {
            assertSame(x, elt);
        });
    };
    Runnable addRemove = () -> {
        while (!done.get()) {
            assertTrue(c.add(elt));
            assertTrue(c.remove(elt));
        }
    };
    Future<?> f1 = pool.submit(checkElt);
    Future<?> f2 = pool.submit(addRemove);
    Thread.sleep(testDurationMillis);
    done.set(true);
    pool.shutdown();
    assertTrue(pool.awaitTermination(LONG_DELAY_MS, MILLISECONDS));
    assertNull(f1.get(LONG_DELAY_MS, MILLISECONDS));
    assertNull(f2.get(LONG_DELAY_MS, MILLISECONDS));
}

68. ConditionalTest#shouldUseTypeMapCondition()

Project: modelmapper
Source File: ConditionalTest.java
View license
public void shouldUseTypeMapCondition() {
    final AtomicBoolean condition = new AtomicBoolean();
    modelMapper.createTypeMap(Source.class, Dest.class).setCondition(new Condition<Object, Object>() {

        public boolean applies(MappingContext<Object, Object> context) {
            return condition.get();
        }
    });
    Source source = new Source();
    source.value = "test";
    // Negative test
    Dest dest = modelMapper.map(source, Dest.class);
    assertEquals(dest.value, null);
    // Positive test
    condition.set(true);
    dest = modelMapper.map(source, Dest.class);
    assertEquals(dest.value, "test");
}

69. QueryUtil#includeFullTextScores()

Project: modeshape
Source File: QueryUtil.java
View license
public static boolean includeFullTextScores(Constraint constraint) {
    final AtomicBoolean includeFullTextScores = new AtomicBoolean(false);
    if (constraint != null) {
        Visitors.visitAll(constraint, new Visitors.AbstractVisitor() {

            @Override
            public void visit(FullTextSearch obj) {
                includeFullTextScores.set(true);
            }
        });
    }
    return includeFullTextScores.get();
}

70. BooleanIndexing#and()

Project: nd4j
Source File: BooleanIndexing.java
View license
/**
     * And over the whole ndarray given some condition
     *
     * @param n    the ndarray to test
     * @param cond the condition to test against
     * @return true if all of the elements meet the specified
     * condition false otherwise
     */
public static boolean and(final INDArray n, final Condition cond) {
    boolean ret = true;
    final AtomicBoolean a = new AtomicBoolean(ret);
    Shape.iterate(n, new CoordinateFunction() {

        @Override
        public void process(int[]... coord) {
            if (a.get())
                a.compareAndSet(true, a.get() && cond.apply(n.getFloat(coord[0])));
        }
    });
    return a.get();
}

71. BooleanIndexing#or()

Project: nd4j
Source File: BooleanIndexing.java
View license
/**
     * Or over the whole ndarray given some condition
     *
     * @param n
     * @param cond
     * @return
     */
public static boolean or(final INDArray n, final Condition cond) {
    boolean ret = false;
    final AtomicBoolean a = new AtomicBoolean(ret);
    Shape.iterate(n, new CoordinateFunction() {

        @Override
        public void process(int[]... coord) {
            if (!a.get())
                a.compareAndSet(false, a.get() || cond.apply(n.getFloat(coord[0])));
        }
    });
    return a.get();
}

72. AsynchronousFlowController#hasActiveReads()

View license
protected boolean hasActiveReads(AllocationPoint point) {
    Queue<cudaEvent_t> events = point.getReadLane();
    if (events.size() == 0)
        return false;
    AtomicBoolean result = new AtomicBoolean(false);
    List<cudaEvent_t> asList = new ArrayList<>(events);
    for (cudaEvent_t event : asList) {
        if (event == null)
            continue;
        // we mark this AllocationPoint is pending read, if at least one event isn't destroyed yet
        result.compareAndSet(false, !event.isDestroyed());
    }
    return result.get();
}

73. EpollReuseAddrTest#testMultipleBindSocketChannel()

Project: netty
Source File: EpollReuseAddrTest.java
View license
@Test(timeout = 10000)
public void testMultipleBindSocketChannel() throws Exception {
    Assume.assumeTrue(versionEqOrGt(3, 9, 0));
    ServerBootstrap bootstrap = createServerBootstrap();
    bootstrap.option(EpollChannelOption.SO_REUSEPORT, true);
    final AtomicBoolean accepted1 = new AtomicBoolean();
    bootstrap.childHandler(new ServerSocketTestHandler(accepted1));
    ChannelFuture future = bootstrap.bind().syncUninterruptibly();
    InetSocketAddress address1 = (InetSocketAddress) future.channel().localAddress();
    final AtomicBoolean accepted2 = new AtomicBoolean();
    bootstrap.childHandler(new ServerSocketTestHandler(accepted2));
    ChannelFuture future2 = bootstrap.bind().syncUninterruptibly();
    InetSocketAddress address2 = (InetSocketAddress) future2.channel().localAddress();
    Assert.assertEquals(address1, address2);
    while (!accepted1.get() || !accepted2.get()) {
        Socket socket = new Socket(address1.getAddress(), address1.getPort());
        socket.setReuseAddress(true);
        socket.close();
    }
    future.channel().close().syncUninterruptibly();
    future2.channel().close().syncUninterruptibly();
}

74. TestConsistentMap#computeIfAbsent()

Project: onos
Source File: TestConsistentMap.java
View license
@Override
public Versioned<V> computeIfAbsent(K key, Function<? super K, ? extends V> mappingFunction) {
    AtomicBoolean updated = new AtomicBoolean(false);
    Versioned<V> result = map.compute(key, ( k,  v) -> {
        if (v == null) {
            updated.set(true);
            return version(mappingFunction.apply(key));
        }
        return v;
    });
    if (updated.get()) {
        notifyListeners(mapName, key, result, null);
    }
    return result;
}

75. TestConsistentMap#compute()

Project: onos
Source File: TestConsistentMap.java
View license
@Override
public Versioned<V> compute(K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction) {
    AtomicBoolean updated = new AtomicBoolean(false);
    AtomicReference<Versioned<V>> previousValue = new AtomicReference<>();
    Versioned<V> result = map.compute(key, ( k,  v) -> {
        updated.set(true);
        previousValue.set(v);
        return version(remappingFunction.apply(k, Versioned.valueOrNull(v)));
    });
    if (updated.get()) {
        notifyListeners(mapName, key, result, previousValue.get());
    }
    return result;
}

76. TestConsistentMap#computeIfPresent()

Project: onos
Source File: TestConsistentMap.java
View license
@Override
public Versioned<V> computeIfPresent(K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction) {
    AtomicBoolean updated = new AtomicBoolean(false);
    AtomicReference<Versioned<V>> previousValue = new AtomicReference<>();
    Versioned<V> result = map.compute(key, ( k,  v) -> {
        if (v != null) {
            updated.set(true);
            previousValue.set(v);
            return version(remappingFunction.apply(k, v.value()));
        }
        return v;
    });
    if (updated.get()) {
        notifyListeners(mapName, key, result, previousValue.get());
    }
    return result;
}

77. TestConsistentMap#computeIf()

Project: onos
Source File: TestConsistentMap.java
View license
@Override
public Versioned<V> computeIf(K key, Predicate<? super V> condition, BiFunction<? super K, ? super V, ? extends V> remappingFunction) {
    AtomicBoolean updated = new AtomicBoolean(false);
    AtomicReference<Versioned<V>> previousValue = new AtomicReference<>();
    Versioned<V> result = map.compute(key, ( k,  v) -> {
        if (condition.test(Versioned.valueOrNull(v))) {
            previousValue.set(v);
            updated.set(true);
            return version(remappingFunction.apply(k, Versioned.valueOrNull(v)));
        }
        return v;
    });
    if (updated.get()) {
        notifyListeners(mapName, key, result, previousValue.get());
    }
    return result;
}

78. DistributedApplicationStore#setPermissions()

View license
@Override
public void setPermissions(ApplicationId appId, Set<Permission> permissions) {
    AtomicBoolean permissionsChanged = new AtomicBoolean(false);
    Versioned<InternalApplicationHolder> appHolder = apps.computeIf(appId,  v -> v != null && !Sets.symmetricDifference(v.permissions(), permissions).isEmpty(), ( k,  v) -> {
        permissionsChanged.set(true);
        return new InternalApplicationHolder(v.app(), v.state(), ImmutableSet.copyOf(permissions));
    });
    if (permissionsChanged.get()) {
        delegate.notify(new ApplicationEvent(APP_PERMISSIONS_CHANGED, appHolder.value().app()));
    }
}

79. EventuallyConsistentMapImpl#putInternal()

View license
/**
     * Returns true if newValue was accepted i.e. map is updated.
     *
     * @param key key
     * @param newValue proposed new value
     * @return true if update happened; false if map already contains a more recent value for the key
     */
private boolean putInternal(K key, MapValue<V> newValue) {
    checkState(!destroyed, destroyedMessage);
    checkNotNull(key, ERROR_NULL_KEY);
    checkNotNull(newValue, ERROR_NULL_VALUE);
    checkState(newValue.isAlive());
    counter.incrementCount();
    AtomicBoolean updated = new AtomicBoolean(false);
    items.compute(key, ( k,  existing) -> {
        if (existing == null || newValue.isNewerThan(existing)) {
            updated.set(true);
            return newValue;
        }
        return existing;
    });
    return updated.get();
}

80. RunFinalizationTest#main()

Project: openjdk
Source File: RunFinalizationTest.java
View license
public static void main(String... args) throws Exception {
    List<String> javaArgs = new ArrayList<>();
    javaArgs.add("-cp");
    javaArgs.add(System.getProperty("test.class.path"));
    javaArgs.add(TEST_APP_NAME);
    ProcessBuilder testAppPb = ProcessTools.createJavaProcessBuilder(javaArgs.toArray(new String[javaArgs.size()]));
    final AtomicBoolean failed = new AtomicBoolean();
    final AtomicBoolean passed = new AtomicBoolean();
    Process runner = ProcessTools.startProcess("FinalizationRunner", testAppPb,  l -> {
        failed.compareAndSet(false, l.contains(FinalizationRunner.FAILED));
        passed.compareAndSet(false, l.contains(FinalizationRunner.PASSED));
    });
    runner.waitFor();
    if (failed.get() || !passed.get()) {
        throw new Error("RunFinalizationTest failed");
    }
}

81. ReachabilityFenceTest#nonFenced()

Project: openjdk
Source File: ReachabilityFenceTest.java
View license
public static boolean nonFenced() {
    AtomicBoolean finalized = new AtomicBoolean();
    MyFinalizeable o = new MyFinalizeable(finalized);
    for (int i = 0; i < LOOP_ITERS; i++) {
        if (finalized.get())
            break;
        if (i > WARMUP_LOOP_ITERS) {
            System.gc();
            System.runFinalization();
        }
    }
    return finalized.get();
}

82. ReachabilityFenceTest#fenced()

Project: openjdk
Source File: ReachabilityFenceTest.java
View license
public static boolean fenced() {
    AtomicBoolean finalized = new AtomicBoolean();
    MyFinalizeable o = new MyFinalizeable(finalized);
    for (int i = 0; i < LOOP_ITERS; i++) {
        if (finalized.get())
            break;
        if (i > WARMUP_LOOP_ITERS) {
            System.gc();
            System.runFinalization();
        }
    }
    Reference.reachabilityFence(o);
    return finalized.get();
}

83. CyclicBarrierTest#testReset_Leakage()

Project: openjdk
Source File: CyclicBarrierTest.java
View license
/**
     * All threads block while a barrier is broken.
     */
public void testReset_Leakage() throws InterruptedException {
    final CyclicBarrier c = new CyclicBarrier(2);
    final AtomicBoolean done = new AtomicBoolean();
    Thread t = newStartedThread(new CheckedRunnable() {

        public void realRun() {
            while (!done.get()) {
                try {
                    while (c.isBroken()) c.reset();
                    c.await();
                    shouldThrow();
                } catch (BrokenBarrierException ok) {
                } catch (InterruptedException ok) {
                }
            }
        }
    });
    for (int i = 0; i < 4; i++) {
        delay(timeoutMillis());
        t.interrupt();
    }
    done.set(true);
    t.interrupt();
    awaitTermination(t);
}

84. LockSupportTest#testParkAfterUnpark()

Project: openjdk
Source File: LockSupportTest.java
View license
public void testParkAfterUnpark(final ParkMethod parkMethod) {
    final CountDownLatch pleaseUnpark = new CountDownLatch(1);
    final AtomicBoolean pleasePark = new AtomicBoolean(false);
    Thread t = newStartedThread(new CheckedRunnable() {

        public void realRun() {
            pleaseUnpark.countDown();
            while (!pleasePark.get()) Thread.yield();
            parkMethod.park();
        }
    });
    await(pleaseUnpark);
    LockSupport.unpark(t);
    pleasePark.set(true);
    awaitTermination(t);
}

85. LockSupportTest#testParkAfterInterrupt()

Project: openjdk
Source File: LockSupportTest.java
View license
public void testParkAfterInterrupt(final ParkMethod parkMethod) {
    final CountDownLatch pleaseInterrupt = new CountDownLatch(1);
    final AtomicBoolean pleasePark = new AtomicBoolean(false);
    Thread t = newStartedThread(new CheckedRunnable() {

        public void realRun() throws Exception {
            pleaseInterrupt.countDown();
            while (!pleasePark.get()) Thread.yield();
            assertTrue(Thread.currentThread().isInterrupted());
            parkMethod.park();
            assertTrue(Thread.currentThread().isInterrupted());
        }
    });
    await(pleaseInterrupt);
    t.interrupt();
    pleasePark.set(true);
    awaitTermination(t);
}

86. NioUdpDataSenderTest#sendMessage_getLimit()

Project: pinpoint
Source File: NioUdpDataSenderTest.java
View license
private boolean sendMessage_getLimit(TBase tbase, long waitTimeMillis) throws InterruptedException {
    final AtomicBoolean limitCounter = new AtomicBoolean(false);
    final CountDownLatch latch = new CountDownLatch(1);
    NioUDPDataSender sender = new NioUDPDataSender("localhost", PORT, "test", 128, 1000, 1024 * 64 * 100);
    try {
        sender.send(tbase);
        latch.await(waitTimeMillis, TimeUnit.MILLISECONDS);
    } finally {
        sender.stop();
    }
    return limitCounter.get();
}

87. UdpDataSenderTest#sendMessage_getLimit()

Project: pinpoint
Source File: UdpDataSenderTest.java
View license
private boolean sendMessage_getLimit(TBase tbase, long waitTimeMillis) throws InterruptedException {
    final AtomicBoolean limitCounter = new AtomicBoolean(false);
    final CountDownLatch latch = new CountDownLatch(1);
    UdpDataSender sender = new UdpDataSender("localhost", PORT, "test", 128, 1000, 1024 * 64 * 100) {

        @Override
        protected boolean isLimit(int interBufferSize) {
            boolean limit = super.isLimit(interBufferSize);
            limitCounter.set(limit);
            latch.countDown();
            return limit;
        }
    };
    try {
        sender.send(tbase);
        latch.await(waitTimeMillis, TimeUnit.MILLISECONDS);
    } finally {
        sender.stop();
    }
    return limitCounter.get();
}

88. SqlQueryManager#addStatsListener()

Project: presto
Source File: SqlQueryManager.java
View license
private void addStatsListener(QueryExecution queryExecution) {
    AtomicBoolean started = new AtomicBoolean();
    queryExecution.addStateChangeListener( newValue -> {
        if (newValue == RUNNING && started.compareAndSet(false, true)) {
            stats.queryStarted();
        }
    });
    // Need to do this check in case the state changed before we added the previous state change listener
    if (queryExecution.getState() == RUNNING && started.compareAndSet(false, true)) {
        stats.queryStarted();
    }
    AtomicBoolean stopped = new AtomicBoolean();
    queryExecution.addStateChangeListener( newValue -> {
        if (newValue.isDone() && stopped.compareAndSet(false, true) && started.get()) {
            stats.queryStopped();
        }
    });
    // Need to do this check in case the state changed before we added the previous state change listener
    if (queryExecution.getState().isDone() && stopped.compareAndSet(false, true) && started.get()) {
        stats.queryStopped();
    }
}

89. FunctionAssertions#needsBoundValue()

Project: presto
Source File: FunctionAssertions.java
View license
private static boolean needsBoundValue(Expression projectionExpression) {
    final AtomicBoolean hasSymbolReferences = new AtomicBoolean();
    new DefaultTraversalVisitor<Void, Void>() {

        @Override
        protected Void visitSymbolReference(SymbolReference node, Void context) {
            hasSymbolReferences.set(true);
            return null;
        }
    }.process(projectionExpression, null);
    return hasSymbolReferences.get();
}

90. LocalKeyValueStoreServiceTest#hasKey()

View license
public boolean hasKey(String key) throws InterruptedException {
    final CountDownLatch getLatch = new CountDownLatch(1);
    final AtomicBoolean reference = new AtomicBoolean();
    kvStore.hasKey( present -> {
        reference.set(present);
        getLatch.countDown();
    }, key);
    Sys.sleep(100);
    ServiceProxyUtils.flushServiceProxy(kvStore);
    getLatch.await(2, TimeUnit.SECONDS);
    return reference.get();
}

91. HttpClientVertxTest#connect()

Project: qbit
Source File: HttpClientVertxTest.java
View license
public void connect() {
    port = PortUtils.findOpenPortStartAt(port);
    server = new HttpServerBuilder().setPort(port).build();
    client = new HttpClientBuilder().setPoolSize(1).setPort(port).build();
    requestReceived = new AtomicBoolean();
    responseReceived = new AtomicBoolean();
    messageBody = new AtomicReference<>();
    responseCode = new AtomicInteger();
    port++;
}

92. AnnotationUtil#hasClassAnnotation()

Project: quasar
Source File: AnnotationUtil.java
View license
private static boolean hasClassAnnotation(Class<? extends Annotation> annClass, ClassReader r) {
    // annotationName = annotationName.replace('.', '/');
    final String annDesc = Type.getDescriptor(annClass);
    final AtomicBoolean res = new AtomicBoolean(false);
    r.accept(new ClassVisitor(ASMAPI) {

        @Override
        public void visit(int version, int access, String name, String signature, String superName, String[] interfaces) {
        }

        @Override
        public AnnotationVisitor visitAnnotation(String desc, boolean visible) {
            if (desc.equals(annDesc))
                res.set(true);
            return null;
        }
    }, ClassReader.SKIP_CODE | ClassReader.SKIP_DEBUG);
    return res.get();
}

93. FiberTest#testCancel1()

Project: quasar
Source File: FiberTest.java
View license
@Test
public void testCancel1() throws Exception {
    final AtomicBoolean started = new AtomicBoolean();
    final AtomicBoolean terminated = new AtomicBoolean();
    Fiber fiber = new Fiber(scheduler, new SuspendableRunnable() {

        @Override
        public void run() throws SuspendExecution {
            started.set(true);
            try {
                Fiber.sleep(100);
                fail("InterruptedException not thrown");
            } catch (InterruptedException e) {
            }
            terminated.set(true);
        }
    });
    fiber.start();
    Thread.sleep(20);
    fiber.cancel(true);
    fiber.join(5, TimeUnit.MILLISECONDS);
    assertThat(started.get(), is(true));
    assertThat(terminated.get(), is(true));
}

94. BaseRealm#deletes()

Project: realm-java
Source File: BaseRealm.java
View license
private static boolean deletes(String canonicalPath, File rootFolder, String realmFileName) {
    final AtomicBoolean realmDeleted = new AtomicBoolean(true);
    List<File> filesToDelete = Arrays.asList(new File(rootFolder, realmFileName), new File(rootFolder, realmFileName + ".lock"), // Old core log file naming styles
    new File(rootFolder, realmFileName + ".log_a"), new File(rootFolder, realmFileName + ".log_b"), new File(rootFolder, realmFileName + ".log"), new File(canonicalPath));
    for (File fileToDelete : filesToDelete) {
        if (fileToDelete.exists()) {
            boolean deleteResult = fileToDelete.delete();
            if (!deleteResult) {
                realmDeleted.set(false);
                RealmLog.w("Could not delete the file " + fileToDelete);
            }
        }
    }
    return realmDeleted.get();
}

95. StreamCompositionTest#testExceptionInClose()

View license
@Test
public void testExceptionInClose() {
    printTestName();
    final AtomicBoolean fClosed = new AtomicBoolean();
    final AtomicBoolean gClosed = new AtomicBoolean();
    boolean gotException = false;
    final Stream<String> f = Stream.of("F").onClose(() -> fClosed.set(true)).onClose(() -> produceException("F"));
    final Stream<String> g = Stream.of("G").onClose(() -> gClosed.set(true)).onClose(() -> produceException("G"));
    List<String> result;
    try {
        result = StreamComposition.concatAndAutoClose(a, b, f, g, c).collect(toList());
    } catch (Exception e) {
        gotException = true;
    }
    assertTrue(gotException);
    assertAllClosed();
    assertTrue(fClosed.get());
    assertTrue(gClosed.get());
}

96. PendingFeatureIterationInterceptor#intercept()

View license
@Override
public void intercept(IMethodInvocation invocation) throws Throwable {
    AtomicBoolean pass = new AtomicBoolean(false);
    invocation.getFeature().getFeatureMethod().addInterceptor(new InnerIterationInterceptor(pass, expectedExceptions));
    invocation.proceed();
    if (pass.get()) {
        throw assumptionViolation();
    } else {
        throw featurePassedUnexpectedly();
    }
}

97. AbstractDefaultTokenServicesTests#testClientInvalidated()

View license
@Test(expected = InvalidTokenException.class)
public void testClientInvalidated() throws Exception {
    final AtomicBoolean deleted = new AtomicBoolean();
    getTokenServices().setClientDetailsService(new ClientDetailsService() {

        public ClientDetails loadClientByClientId(String clientId) throws OAuth2Exception {
            if (deleted.get()) {
                throw new ClientRegistrationException("No such client: " + clientId);
            }
            BaseClientDetails client = new BaseClientDetails();
            client.setRefreshTokenValiditySeconds(100);
            client.setAuthorizedGrantTypes(Arrays.asList("authorization_code", "refresh_token"));
            return client;
        }
    });
    OAuth2AccessToken token = getTokenServices().createAccessToken(createAuthentication());
    deleted.set(true);
    OAuth2Authentication authentication = getTokenServices().loadAuthentication(token.getValue());
    assertNotNull(authentication.getOAuth2Request());
}

98. QueryTest#testAtomicBoolean()

Project: squidb
Source File: QueryTest.java
View license
public void testAtomicBoolean() {
    AtomicBoolean isHappy = new AtomicBoolean(false);
    Query query = Query.select().where(Employee.IS_HAPPY.eq(isHappy));
    SquidCursor<Employee> unhappyEmployee = database.query(Employee.class, query);
    try {
        assertEquals(1, unhappyEmployee.getCount());
        unhappyEmployee.moveToFirst();
        assertEquals(oscar.getId(), unhappyEmployee.get(Employee.ID).longValue());
    } finally {
        unhappyEmployee.close();
    }
    isHappy.set(true);
    SquidCursor<Employee> happyEmployees = database.query(Employee.class, query);
    try {
        assertEquals(5, happyEmployees.getCount());
    } finally {
        happyEmployees.close();
    }
}

99. InputReadyVertexManager#initialize()

Project: tez
Source File: InputReadyVertexManager.java
View license
@Override
public void initialize() {
    // this will prevent vertex from starting until we notify we are done
    getContext().vertexReconfigurationPlanned();
    Map<String, EdgeProperty> edges = getContext().getInputVertexEdgeProperties();
    // wait for sources and self to start
    numConfiguredSources = 0;
    configured = new AtomicBoolean(false);
    started = new AtomicBoolean(false);
    for (String entry : edges.keySet()) {
        getContext().registerForVertexStateUpdates(entry, EnumSet.of(VertexState.CONFIGURED));
    }
}

100. ServicesTest#testCompletion()

Project: weave
Source File: ServicesTest.java
View license
@Test
public void testCompletion() throws ExecutionException, InterruptedException {
    Service service = new DummyService("s1", new AtomicBoolean());
    ListenableFuture<Service.State> completion = Services.getCompletionFuture(service);
    service.start();
    service.stop();
    completion.get();
    AtomicBoolean transiting = new AtomicBoolean();
    service = new DummyService("s2", transiting);
    completion = Services.getCompletionFuture(service);
    service.startAndWait();
    transiting.set(true);
    service.stop();
    try {
        completion.get();
        Assert.assertTrue(false);
    } catch (ExecutionException e) {
    }
}