Search in sources :

Example 41 with Semaphore

use of java.util.concurrent.Semaphore in project FirebaseUI-Android by firebase.

the class TestUtils method runAndWaitUntil.

public static void runAndWaitUntil(FirebaseArray array, Runnable task, Callable<Boolean> done) throws InterruptedException {
    final Semaphore semaphore = new Semaphore(0);
    array.setOnChangedListener(new ChangeEventListener() {

        @Override
        public void onChildChanged(ChangeEventListener.EventType type, int index, int oldIndex) {
            semaphore.release();
        }

        @Override
        public void onDataChanged() {
        }

        @Override
        public void onCancelled(DatabaseError error) {
            throw new IllegalStateException(error.toException());
        }
    });
    task.run();
    boolean isDone = false;
    long startedAt = System.currentTimeMillis();
    while (!isDone && System.currentTimeMillis() - startedAt < TIMEOUT) {
        semaphore.tryAcquire(1, TimeUnit.SECONDS);
        try {
            isDone = done.call();
        } catch (Exception e) {
            e.printStackTrace();
        // and we're not done
        }
    }
    assertTrue("Timed out waiting for expected results on FirebaseArray", isDone);
    array.setOnChangedListener(null);
}
Also used : DatabaseError(com.google.firebase.database.DatabaseError) Semaphore(java.util.concurrent.Semaphore)

Example 42 with Semaphore

use of java.util.concurrent.Semaphore in project libstreaming by fyhertz.

the class RtpSocket method resetFifo.

private void resetFifo() {
    mCount = 0;
    mBufferIn = 0;
    mBufferOut = 0;
    mTimestamps = new long[mBufferCount];
    mBufferRequested = new Semaphore(mBufferCount);
    mBufferCommitted = new Semaphore(0);
    mReport.reset();
    mAverageBitrate.reset();
}
Also used : Semaphore(java.util.concurrent.Semaphore)

Example 43 with Semaphore

use of java.util.concurrent.Semaphore in project pulsar by yahoo.

the class HttpDestinationLookupv2Test method setUp.

@SuppressWarnings("unchecked")
@BeforeMethod
public void setUp() throws Exception {
    pulsar = mock(PulsarService.class);
    ns = mock(NamespaceService.class);
    auth = mock(AuthorizationManager.class);
    mockConfigCache = mock(ConfigurationCacheService.class);
    clustersListCache = mock(ZooKeeperChildrenCache.class);
    clustersCache = mock(ZooKeeperDataCache.class);
    policiesCache = mock(ZooKeeperDataCache.class);
    config = spy(new ServiceConfiguration());
    config.setClusterName("use");
    clusters = new TreeSet<String>();
    clusters.add("use");
    clusters.add("usc");
    clusters.add("usw");
    ClusterData useData = new ClusterData("http://broker.messaging.use.example.com:8080");
    ClusterData uscData = new ClusterData("http://broker.messaging.usc.example.com:8080");
    ClusterData uswData = new ClusterData("http://broker.messaging.usw.example.com:8080");
    doReturn(config).when(pulsar).getConfiguration();
    doReturn(mockConfigCache).when(pulsar).getConfigurationCache();
    doReturn(clustersListCache).when(mockConfigCache).clustersListCache();
    doReturn(clustersCache).when(mockConfigCache).clustersCache();
    doReturn(policiesCache).when(mockConfigCache).policiesCache();
    doReturn(Optional.of(useData)).when(clustersCache).get(AdminResource.path("clusters", "use"));
    doReturn(Optional.of(uscData)).when(clustersCache).get(AdminResource.path("clusters", "usc"));
    doReturn(Optional.of(uswData)).when(clustersCache).get(AdminResource.path("clusters", "usw"));
    doReturn(CompletableFuture.completedFuture(Optional.of(useData))).when(clustersCache).getAsync(AdminResource.path("clusters", "use"));
    doReturn(CompletableFuture.completedFuture(Optional.of(uscData))).when(clustersCache).getAsync(AdminResource.path("clusters", "usc"));
    doReturn(CompletableFuture.completedFuture(Optional.of(uswData))).when(clustersCache).getAsync(AdminResource.path("clusters", "usw"));
    doReturn(clusters).when(clustersListCache).get();
    doReturn(ns).when(pulsar).getNamespaceService();
    BrokerService brokerService = mock(BrokerService.class);
    doReturn(brokerService).when(pulsar).getBrokerService();
    doReturn(auth).when(brokerService).getAuthorizationManager();
    doReturn(new Semaphore(1000)).when(brokerService).getLookupRequestSemaphore();
}
Also used : ClusterData(com.yahoo.pulsar.common.policies.data.ClusterData) PulsarService(com.yahoo.pulsar.broker.PulsarService) NamespaceService(com.yahoo.pulsar.broker.namespace.NamespaceService) ServiceConfiguration(com.yahoo.pulsar.broker.ServiceConfiguration) ConfigurationCacheService(com.yahoo.pulsar.broker.cache.ConfigurationCacheService) ZooKeeperChildrenCache(com.yahoo.pulsar.zookeeper.ZooKeeperChildrenCache) AuthorizationManager(com.yahoo.pulsar.broker.authorization.AuthorizationManager) ZooKeeperDataCache(com.yahoo.pulsar.zookeeper.ZooKeeperDataCache) Semaphore(java.util.concurrent.Semaphore) BrokerService(com.yahoo.pulsar.broker.service.BrokerService) BeforeMethod(org.testng.annotations.BeforeMethod)

Example 44 with Semaphore

use of java.util.concurrent.Semaphore in project android-priority-jobqueue by yigit.

the class LoadFactorTest method testLoadFactor.

@Test
public void testLoadFactor() throws Exception {
    //test adding zillions of jobs from the same group and ensure no more than 1 thread is created
    int maxConsumerCount = 5;
    int minConsumerCount = 2;
    int loadFactor = 5;
    enableDebug();
    JobManager jobManager = createJobManager(new Configuration.Builder(RuntimeEnvironment.application).maxConsumerCount(maxConsumerCount).minConsumerCount(minConsumerCount).loadFactor(loadFactor).timer(mockTimer));
    final CountDownLatch runLock = new CountDownLatch(1);
    Semaphore semaphore = new Semaphore(maxConsumerCount);
    int totalJobCount = loadFactor * maxConsumerCount * 5;
    List<DummyJob> runningJobs = new ArrayList<DummyJob>(totalJobCount);
    int prevConsumerCount = 0;
    final Semaphore onRunCount = new Semaphore(totalJobCount);
    onRunCount.acquire(totalJobCount);
    for (int i = 0; i < totalJobCount; i++) {
        DummyJob job = new NeverEndingDummyJob(new Params((int) (Math.random() * 3)), runLock, semaphore) {

            @Override
            public void onRun() throws Throwable {
                onRunCount.release();
                super.onRun();
            }
        };
        runningJobs.add(job);
        jobManager.addJob(job);
        final int wantedConsumers = (int) Math.ceil((i + 1f) / loadFactor);
        final int expectedConsumerCount = Math.max(Math.min(i + 1, minConsumerCount), Math.min(maxConsumerCount, wantedConsumers));
        if (prevConsumerCount != expectedConsumerCount) {
            assertThat("waiting for another job to start", onRunCount.tryAcquire(1, 10, TimeUnit.SECONDS), is(true));
        }
        assertThat("Consumer count should match expected value at " + (i + 1) + " jobs", jobManager.getActiveConsumerCount(), equalTo(expectedConsumerCount));
        prevConsumerCount = expectedConsumerCount;
    }
    //finish all jobs
    waitUntilJobsAreDone(jobManager, runningJobs, new Runnable() {

        @Override
        public void run() {
            runLock.countDown();
        }
    });
    assertThat("no jobs should remain", jobManager.count(), equalTo(0));
}
Also used : Configuration(com.birbit.android.jobqueue.config.Configuration) ArrayList(java.util.ArrayList) Params(com.birbit.android.jobqueue.Params) JobManager(com.birbit.android.jobqueue.JobManager) Semaphore(java.util.concurrent.Semaphore) CountDownLatch(java.util.concurrent.CountDownLatch) SuppressLint(android.annotation.SuppressLint) Constraint(com.birbit.android.jobqueue.Constraint) DummyJob(com.birbit.android.jobqueue.test.jobs.DummyJob) Test(org.junit.Test)

Example 45 with Semaphore

use of java.util.concurrent.Semaphore in project android-priority-jobqueue by yigit.

the class ConsumerCountTest method testMaxConsumerCount.

@Test
public void testMaxConsumerCount() throws Exception {
    int maxConsumerCount = 2;
    JobManager jobManager = createJobManager(new Configuration.Builder(RuntimeEnvironment.application).maxConsumerCount(maxConsumerCount).loadFactor(maxConsumerCount).timer(mockTimer));
    Semaphore semaphore = new Semaphore(maxConsumerCount);
    int totalJobCount = maxConsumerCount * 3;
    List<NeverEndingDummyJob> runningJobs = new ArrayList<>(totalJobCount);
    for (int i = 0; i < totalJobCount; i++) {
        NeverEndingDummyJob job = new NeverEndingDummyJob(new Params((int) (Math.random() * 3)), runLock, semaphore);
        runningJobs.add(job);
        jobManager.addJob(job);
    }
    Timer timer = new SystemTimer();
    //wait till enough jobs start
    long start = timer.nanoTime();
    long tenSeconds = TimeUnit.SECONDS.toNanos(10);
    while (timer.nanoTime() - start < tenSeconds && semaphore.tryAcquire()) {
        semaphore.release();
        //noinspection SLEEP_IN_CODE
        Thread.sleep(100);
    }
    MatcherAssert.assertThat("all consumers should start in 10 seconds", timer.nanoTime() - start > tenSeconds, is(false));
    //wait some more to ensure no more jobs are started
    //noinspection SLEEP_IN_CODE
    Thread.sleep(TimeUnit.SECONDS.toMillis(3));
    int totalRunningCount = 0;
    for (DummyJob job : runningJobs) {
        totalRunningCount += job.getOnRunCnt();
    }
    MatcherAssert.assertThat("only maxConsumerCount jobs should start", totalRunningCount, equalTo(maxConsumerCount));
    waitUntilJobsAreDone(jobManager, runningJobs, new Runnable() {

        @Override
        public void run() {
            runLock.countDown();
        }
    });
    MatcherAssert.assertThat("no jobs should remain", jobManager.count(), equalTo(0));
}
Also used : ArrayList(java.util.ArrayList) Params(com.birbit.android.jobqueue.Params) JobManager(com.birbit.android.jobqueue.JobManager) Semaphore(java.util.concurrent.Semaphore) SystemTimer(com.birbit.android.jobqueue.timer.SystemTimer) Timer(com.birbit.android.jobqueue.timer.Timer) DummyJob(com.birbit.android.jobqueue.test.jobs.DummyJob) SystemTimer(com.birbit.android.jobqueue.timer.SystemTimer) Test(org.junit.Test)

Aggregations

Semaphore (java.util.concurrent.Semaphore)511 Test (org.junit.Test)198 IOException (java.io.IOException)55 Context (android.content.Context)39 InvocationOnMock (org.mockito.invocation.InvocationOnMock)38 ArrayList (java.util.ArrayList)37 HashMap (java.util.HashMap)36 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)31 AtomicReference (java.util.concurrent.atomic.AtomicReference)31 ExecutionException (java.util.concurrent.ExecutionException)30 File (java.io.File)29 Intent (android.content.Intent)27 List (java.util.List)27 Map (java.util.Map)26 CountDownLatch (java.util.concurrent.CountDownLatch)25 Handler (android.os.Handler)24 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)24 HazelcastInstance (com.hazelcast.core.HazelcastInstance)21 BroadcastReceiver (android.content.BroadcastReceiver)20 IntentFilter (android.content.IntentFilter)20