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);
}
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();
}
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();
}
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));
}
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));
}
Aggregations