Search in sources :

Example 1 with Timer

use of com.birbit.android.jobqueue.timer.Timer 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

JobManager (com.birbit.android.jobqueue.JobManager)1 Params (com.birbit.android.jobqueue.Params)1 DummyJob (com.birbit.android.jobqueue.test.jobs.DummyJob)1 SystemTimer (com.birbit.android.jobqueue.timer.SystemTimer)1 Timer (com.birbit.android.jobqueue.timer.Timer)1 ArrayList (java.util.ArrayList)1 Semaphore (java.util.concurrent.Semaphore)1 Test (org.junit.Test)1