Java Code Examples for java.util.concurrent.Semaphore#availablePermits()

The following examples show how to use java.util.concurrent.Semaphore#availablePermits() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: AccessRestrictedServlet.java    From bugu-mongo with Apache License 2.0 6 votes vote down vote up
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    Semaphore semaphore = AccessCount.getInstance().getSemaphore(resourceName, maxAccess);
    if(!StringUtil.isEmpty(redirectTo) && semaphore.availablePermits()<=0){
        response.sendRedirect(redirectTo);
    }
    else{
        try{
            semaphore.acquire();
            processRequest(request, response);
        }catch(IOException | InterruptedException | ServletException ex){
            throw new BuguFSException(ex.getMessage());
        }finally{
            semaphore.release();
        }
    }
}
 
Example 2
Source File: SemaphoreManager.java    From aliyun-tsdb-java-sdk with Apache License 2.0 5 votes vote down vote up
public boolean removeAddress(String address) {
	Semaphore semaphore = this.addressSemaphoreMap.get(address);
	if (semaphore.availablePermits() == this.poolNum) {
		this.addressSemaphoreMap.remove(address);
		return true;
	}
	return false;
}
 
Example 3
Source File: SemaphoreTest.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
public void testReleaseAcquireDifferentThreads(boolean fair,
                                               final AcquireMethod acquirer) {
    final Semaphore s = new Semaphore(0, fair);
    final int rounds = 4;
    long startTime = System.nanoTime();
    Thread t = newStartedThread(new CheckedRunnable() {
        public void realRun() throws InterruptedException {
            for (int i = 0; i < rounds; i++) {
                assertFalse(s.hasQueuedThreads());
                if (i % 2 == 0)
                    acquirer.acquire(s);
                else
                    acquirer.acquire(s, 3);
            }}});

    for (int i = 0; i < rounds; i++) {
        while (! (s.availablePermits() == 0 && s.hasQueuedThreads()))
            Thread.yield();
        assertTrue(t.isAlive());
        if (i % 2 == 0)
            s.release();
        else
            s.release(3);
    }
    awaitTermination(t);
    assertEquals(0, s.availablePermits());
    assertTrue(millisElapsedSince(startTime) < LONG_DELAY_MS);
}
 
Example 4
Source File: SemaphoreTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
public void testReleaseAcquireDifferentThreads(boolean fair,
                                               final AcquireMethod acquirer) {
    final Semaphore s = new Semaphore(0, fair);
    final int rounds = 4;
    long startTime = System.nanoTime();
    Thread t = newStartedThread(new CheckedRunnable() {
        public void realRun() throws InterruptedException {
            for (int i = 0; i < rounds; i++) {
                assertFalse(s.hasQueuedThreads());
                if (i % 2 == 0)
                    acquirer.acquire(s);
                else
                    acquirer.acquire(s, 3);
            }}});

    for (int i = 0; i < rounds; i++) {
        while (! (s.availablePermits() == 0 && s.hasQueuedThreads()))
            Thread.yield();
        assertTrue(t.isAlive());
        if (i % 2 == 0)
            s.release();
        else
            s.release(3);
    }
    awaitTermination(t);
    assertEquals(0, s.availablePermits());
    assertTrue(millisElapsedSince(startTime) < LONG_DELAY_MS);
}
 
Example 5
Source File: AccessCount.java    From bugu-mongo with Apache License 2.0 5 votes vote down vote up
/**
 * Get the available count allowed to access.
 * @param resourceName
 * @return 
 */
public int getAvailablePermits(String resourceName){
    int count = Integer.MAX_VALUE;
    Semaphore semaphore = map.get(resourceName);
    if(semaphore != null){
        count = semaphore.availablePermits();
    }
    return count;
}
 
Example 6
Source File: TestRecoveryHdfs.java    From lucene-solr with Apache License 2.0 4 votes vote down vote up
@Test
public void testLogReplay() throws Exception {
  try {
    TestInjection.skipIndexWriterCommitOnClose = true;
    final Semaphore logReplay = new Semaphore(0);
    final Semaphore logReplayFinish = new Semaphore(0);

    UpdateLog.testing_logReplayHook = () -> {
      try {
        assertTrue(logReplay.tryAcquire(TIMEOUT, TimeUnit.SECONDS));
      } catch (Exception e) {
        throw new RuntimeException(e);
      }
    };

    UpdateLog.testing_logReplayFinishHook = logReplayFinish::release;

    clearIndex();
    assertU(commit());

    Deque<Long> versions = new ArrayDeque<>();
    versions.addFirst(addAndGetVersion(sdoc("id", "A1"), null));
    versions.addFirst(addAndGetVersion(sdoc("id", "A11"), null));
    versions.addFirst(addAndGetVersion(sdoc("id", "A12"), null));
    versions.addFirst(deleteByQueryAndGetVersion("id:A11", null));
    versions.addFirst(addAndGetVersion(sdoc("id", "A13"), null));

    assertJQ(req("q","*:*"),"/response/numFound==0");

    assertJQ(req("qt","/get", "getVersions",""+versions.size()) ,"/versions==" + versions);

    h.close();
    createCore();
    // Solr should kick this off now
    // h.getCore().getUpdateHandler().getUpdateLog().recoverFromLog();

    // verify that previous close didn't do a commit
    // recovery should be blocked by our hook
    assertJQ(req("q","*:*") ,"/response/numFound==0");

    // make sure we can still access versions after a restart
    assertJQ(req("qt","/get", "getVersions",""+versions.size()),"/versions==" + versions);

    // unblock recovery
    logReplay.release(1000);

    // make sure we can still access versions during recovery
    assertJQ(req("qt","/get", "getVersions",""+versions.size()),"/versions==" + versions);

    // wait until recovery has finished
    assertTrue(logReplayFinish.tryAcquire(TIMEOUT, TimeUnit.SECONDS));

    assertJQ(req("q","*:*") ,"/response/numFound==3");

    // make sure we can still access versions after recovery
    assertJQ(req("qt","/get", "getVersions",""+versions.size()) ,"/versions==" + versions);

    assertU(adoc("id","A2"));
    assertU(adoc("id","A3"));
    assertU(delI("A2"));
    assertU(adoc("id","A4"));

    assertJQ(req("q","*:*") ,"/response/numFound==3");

    h.close();
    createCore();
    // Solr should kick this off now
    // h.getCore().getUpdateHandler().getUpdateLog().recoverFromLog();

    // wait until recovery has finished
    assertTrue(logReplayFinish.tryAcquire(TIMEOUT, TimeUnit.SECONDS));
    assertJQ(req("q","*:*") ,"/response/numFound==5");
    assertJQ(req("q","id:A2") ,"/response/numFound==0");

    // no updates, so insure that recovery does not run
    h.close();
    int permits = logReplay.availablePermits();
    createCore();
    // Solr should kick this off now
    // h.getCore().getUpdateHandler().getUpdateLog().recoverFromLog();

    assertJQ(req("q","*:*") ,"/response/numFound==5");
    Thread.sleep(100);
    assertEquals(permits, logReplay.availablePermits()); // no updates, so insure that recovery didn't run

    assertEquals(UpdateLog.State.ACTIVE, h.getCore().getUpdateHandler().getUpdateLog().getState());

  } finally {
    UpdateLog.testing_logReplayHook = null;
    UpdateLog.testing_logReplayFinishHook = null;
  }
}
 
Example 7
Source File: TestBoundedInMemoryQueue.java    From hudi with Apache License 2.0 4 votes vote down vote up
private boolean isQueueFull(Semaphore rateLimiter) {
  return (rateLimiter.availablePermits() == 0 && rateLimiter.hasQueuedThreads());
}