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

The following examples show how to use java.util.concurrent.Semaphore#tryAcquire() . 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: LimiterInterceptor.java    From jboot with Apache License 2.0 6 votes vote down vote up
private void doInterceptForConcurrency(int rate, String resource, String fallback, Invocation inv) {
    Semaphore semaphore = LimiterManager.me().getOrCreateSemaphore(resource, rate);
    boolean acquire = false;
    try {
        acquire = semaphore.tryAcquire();
        if (acquire) {
            inv.invoke();
        }
        //不允许通行
        else {
            doExecFallback(resource, fallback, inv);
        }
    } finally {
        if (acquire) {
            semaphore.release();
        }
    }
}
 
Example 2
Source File: LocalHistoryStoreImpl.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@Override
public void waitForProcessedStoring(VCSFileProxy file, String caller) {
    Semaphore s;
    synchronized(proccessedFiles) {
        s = proccessedFiles.get(file);
    }
    if(s != null) {
        long l = System.currentTimeMillis();
        try {
            long t9Timeout = getT9LockReleaseTimeOut();
            long timeout = t9Timeout >= 0 ? t9Timeout : LOCK_TIMEOUT;
            boolean aquired = s.tryAcquire(timeout, TimeUnit.SECONDS);
            if(aquired) {
                s.release();
            } else {
                LOG.log(Level.WARNING, "{0} Releasing lock on file: {1}", new Object[] {caller, FileUtils.getPath(file)}); // NOI18N
                synchronized(proccessedFiles) {
                    proccessedFiles.remove(file);
                }
            }
        } catch (InterruptedException ex) {
            // nothing
        }
        LOG.log(Level.FINER, "{0} for file {1} was blocked {2} millis.", new Object[] {caller, FileUtils.getPath(file), System.currentTimeMillis() - l}); // NOI18N
    }
}
 
Example 3
Source File: FileWatchServiceTest.java    From rocketmq with Apache License 2.0 6 votes vote down vote up
@Test
public void watchSingleFile_FileDeleted() throws Exception {
    File file = tempFolder.newFile();
    final Semaphore waitSemaphore = new Semaphore(0);
    FileWatchService fileWatchService = new FileWatchService(new String[] {file.getAbsolutePath()},
        new FileWatchService.Listener() {
        @Override
        public void onChanged(String path) {
            waitSemaphore.release();
        }
    });
    fileWatchService.start();
    file.delete();
    boolean result = waitSemaphore.tryAcquire(1, 1000, TimeUnit.MILLISECONDS);
    assertThat(result).isFalse();
    file.createNewFile();
    modifyFile(file);
    result = waitSemaphore.tryAcquire(1, 2000, TimeUnit.MILLISECONDS);
    assertThat(result).isTrue();
}
 
Example 4
Source File: CleanerTest.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Check a semaphore having been released by cleanup handler.
 * Force a number of GC cycles to give the GC a chance to process
 * the Reference and for the cleanup action to be run.
 * Use a larger number of cycles to wait for an expected cleaning to occur.
 *
 * @param semaphore a Semaphore
 * @param expectCleaned true if cleaning should occur
 * @param msg a message to explain the error
 */
static void checkCleaned(Semaphore semaphore, boolean expectCleaned,
                         String msg) {
    long max_cycles = expectCleaned ? 10 : 3;
    long cycle = 0;
    for (; cycle < max_cycles; cycle++) {
        // Force GC
        whitebox.fullGC();

        try {
            if (semaphore.tryAcquire(Utils.adjustTimeout(10L), TimeUnit.MILLISECONDS)) {
                System.out.printf(" Cleanable cleaned in cycle: %d%n", cycle);
                Assert.assertEquals(true, expectCleaned, msg);
                return;
            }
        } catch (InterruptedException ie) {
            // retry in outer loop
        }
    }
    // Object has not been cleaned
    Assert.assertEquals(false, expectCleaned, msg);
}
 
Example 5
Source File: JobExecutorTest.java    From jobson with Apache License 2.0 6 votes vote down vote up
@Test
public void testExecuteEvaluatesToStringAsExpected() throws InterruptedException {
    final JobExecutor jobExecutor = getInstance();
    final PersistedJob req =
            standardRequestWithCommand("echo", "${toString(inputs.someString)}");
    final AtomicReference<byte[]> bytesEchoedToStdout = new AtomicReference<>(new byte[]{});
    final Subject<byte[]> stdoutSubject = PublishSubject.create();
    stdoutSubject.subscribe(bytes ->
            bytesEchoedToStdout.getAndUpdate(existingBytes ->
                    Bytes.concat(existingBytes, bytes)));

    final Semaphore s = new Semaphore(1);
    s.acquire();
    stdoutSubject.doOnComplete(s::release).subscribe();

    final JobEventListeners listeners =
            createStdoutListener(stdoutSubject);

    jobExecutor.execute(req, listeners);

    s.tryAcquire(TestConstants.DEFAULT_TIMEOUT, MILLISECONDS);

    final String stringFromStdout = new String(bytesEchoedToStdout.get()).trim();

    assertThat(stringFromStdout).isEqualTo("hello, world!"); // from input fixture
}
 
Example 6
Source File: FileWatchServiceTest.java    From rocketmq-4.3.0 with Apache License 2.0 6 votes vote down vote up
@Test
public void watchSingleFile() throws Exception {
    final File file = tempFolder.newFile();
    final Semaphore waitSemaphore = new Semaphore(0);
    FileWatchService fileWatchService = new FileWatchService(new String[] {file.getAbsolutePath()}, new FileWatchService.Listener() {
        @Override
        public void onChanged(String path) {
            assertThat(file.getAbsolutePath()).isEqualTo(path);
            waitSemaphore.release();
        }
    });
    fileWatchService.start();
    modifyFile(file);
    boolean result = waitSemaphore.tryAcquire(1, 1000, TimeUnit.MILLISECONDS);
    assertThat(result).isTrue();
}
 
Example 7
Source File: Uninterruptibles.java    From codebuff with BSD 2-Clause "Simplified" License 6 votes vote down vote up
/**
 * Invokes {@code semaphore.}{@link Semaphore#tryAcquire(int, long, TimeUnit) tryAcquire(permits,
 * timeout, unit)} uninterruptibly.
 *
 * @since 18.0
 */

@GwtIncompatible // concurrency
public static boolean tryAcquireUninterruptibly(Semaphore semaphore, int permits, long timeout, TimeUnit unit) {
  boolean interrupted = false;
  try {
    long remainingNanos = unit.toNanos(timeout);
    long end = System.nanoTime() + remainingNanos;
    while (true) {
      try {
        // Semaphore treats negative timeouts just like zero.
        return semaphore.tryAcquire(permits, remainingNanos, NANOSECONDS);
      } catch (InterruptedException e) {
        interrupted = true;
        remainingNanos = end - System.nanoTime();
      }
    }
  } finally {
    if (interrupted) {
      Thread.currentThread().interrupt();
    }
  }
}
 
Example 8
Source File: FileWatchServiceTest.java    From rocketmq-4.3.0 with Apache License 2.0 6 votes vote down vote up
@Test
public void watchTwoFiles_ModifyOne() throws Exception {
    final File fileA = tempFolder.newFile();
    File fileB = tempFolder.newFile();
    final Semaphore waitSemaphore = new Semaphore(0);
    FileWatchService fileWatchService = new FileWatchService(
        new String[] {fileA.getAbsolutePath(), fileB.getAbsolutePath()},
        new FileWatchService.Listener() {
        @Override
        public void onChanged(String path) {
            assertThat(path).isEqualTo(fileA.getAbsolutePath());
            waitSemaphore.release();
        }
    });
    fileWatchService.start();
    modifyFile(fileA);
    boolean result = waitSemaphore.tryAcquire(1, 1000, TimeUnit.MILLISECONDS);
    assertThat(result).isTrue();
}
 
Example 9
Source File: BleOtaUpdater.java    From Android-BLE with Apache License 2.0 6 votes vote down vote up
/**
 * Wait for the lock to release
 * @param semp Lock object
 * @return Whether it is overtime
 */
private boolean waitSemaphore(Semaphore semp) {
	int i = 0;

	do {
		if (i++ >= mTimeout * 1000) {
			return false;
		}

		boolean getAccquire = semp.tryAcquire();
		if (getAccquire) {
			return true;
		}

		try {
			Thread.sleep(1L);
		} catch (InterruptedException e) {
			if(BuildConfig.DEBUG) {
				e.printStackTrace();
			}
			return true;
		}
	} while (!this.shouldStopUpdate());//Has stopped updating

	return false;
}
 
Example 10
Source File: Uninterruptibles.java    From codebuff with BSD 2-Clause "Simplified" License 6 votes vote down vote up
/**
 * Invokes {@code semaphore.}{@link Semaphore#tryAcquire(int, long, TimeUnit) tryAcquire(permits,
 * timeout, unit)} uninterruptibly.
 *
 * @since 18.0
 */

@GwtIncompatible // concurrency
public static boolean tryAcquireUninterruptibly(Semaphore semaphore, int permits, long timeout, TimeUnit unit) {
  boolean interrupted = false;
  try {
    long remainingNanos = unit.toNanos(timeout);
    long end = System.nanoTime() + remainingNanos;
    while (true) {
      try {
        // Semaphore treats negative timeouts just like zero.
        return semaphore.tryAcquire(permits, remainingNanos, NANOSECONDS);
      } catch (InterruptedException e) {
        interrupted = true;
        remainingNanos = end - System.nanoTime();
      }
    }
  } finally {
    if (interrupted) {
      Thread.currentThread().interrupt();
    }
  }
}
 
Example 11
Source File: CcMessageRouterTest.java    From joynr with Apache License 2.0 5 votes vote down vote up
@Test
public void testMessageProcessedListenerCalledOnSuccess() throws Exception {
    final Semaphore semaphore = new Semaphore(0);

    joynrMessage.setTtlMs(ExpiryDate.fromRelativeTtl(100000000).getValue());
    joynrMessage.setTtlAbsolute(true);
    final ImmutableMessage immutableMessage = joynrMessage.getImmutableMessage();

    final MessageProcessedListener mockMessageProcessedListener = mock(MessageProcessedListener.class);
    messageRouter.registerMessageProcessedListener(mockMessageProcessedListener);

    doAnswer(new Answer<Void>() {
        @Override
        public Void answer(InvocationOnMock invocation) throws Throwable {
            verify(mockMessageProcessedListener, times(0)).messageProcessed(eq(immutableMessage.getId()));
            invocation.getArgumentAt(1, SuccessAction.class).execute();
            semaphore.release();
            return null;
        }
    }).when(messagingStubMock)
      .transmit(any(ImmutableMessage.class), any(SuccessAction.class), any(FailureAction.class));

    messageRouter.route(immutableMessage);

    semaphore.tryAcquire(1000, TimeUnit.MILLISECONDS);
    verify(mockMessageProcessedListener).messageProcessed(eq(immutableMessage.getId()));
}
 
Example 12
Source File: InMemoryConcurrentRequestRateLimiter.java    From ratelimitj with Apache License 2.0 5 votes vote down vote up
@Override
public Baton acquire(String key, final int weight) {
    final Semaphore semaphore = expiringKeyMap.computeIfAbsent(key, s -> new Semaphore(rule.getConcurrentLimit(), false));
    if (semaphore.tryAcquire(weight)) {

        // TODO the semaphore needs to expire the if never closed
        return new InMemoryBaton(semaphore, weight);
    }
    return new InMemoryBaton(weight);
}
 
Example 13
Source File: Timing2.java    From curator with Apache License 2.0 5 votes vote down vote up
/**
 * Wait on the given semaphore
 *
 * @param semaphore the semaphore
 * @param n         number of permits to acquire
 * @return result of {@link java.util.concurrent.Semaphore#tryAcquire(int, long, java.util.concurrent.TimeUnit)}
 */
public boolean acquireSemaphore(Semaphore semaphore, int n)
{
    Timing2 m = forWaiting();
    try
    {
        return semaphore.tryAcquire(n, m.value, m.unit);
    }
    catch ( InterruptedException e )
    {
        Thread.currentThread().interrupt();
    }
    return false;
}
 
Example 14
Source File: RefreshableTest.java    From flutter-intellij with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private void acquireOrLog(Semaphore s, String error) {
  try {
    if (!s.tryAcquire(1, TimeUnit.SECONDS)) {
      log(error);
    }
  } catch (InterruptedException e) {
    log(error + " (interrupted)");
  }
}
 
Example 15
Source File: DownloadTest.java    From firebase-android-sdk with Apache License 2.0 4 votes vote down vote up
@Test
public void streamDownloadStateVerification() throws Exception {
  System.out.println("Starting test streamDownloadStateVerification.");

  NetworkLayerMock.ensureNetworkMock("streamDownload", true);
  final Semaphore semaphore = new Semaphore(0);

  StorageReference storage = FirebaseStorage.getInstance().getReference("image.jpg");

  final AtomicLong bytesDownloaded = new AtomicLong();
  final AtomicLong bytesTransferred = new AtomicLong();
  final int fileSize = 1076408;

  ControllableSchedulerHelper.getInstance().pause();

  final StreamDownloadTask task =
      storage.getStream(
          (state, stream) -> {
            Assert.assertEquals(0, state.getBytesTransferred());
            Assert.assertEquals(fileSize, state.getTotalByteCount());

            byte[] buffer = new byte[256];

            int length;
            while ((length = stream.read(buffer)) != -1) {
              bytesDownloaded.addAndGet(length);
              Assert.assertEquals(fileSize, state.getTotalByteCount());
            }

            Assert.assertEquals(bytesDownloaded.get(), state.getTotalByteCount());
            stream.close();
            semaphore.release(1);
          });

  task.addOnProgressListener(state -> bytesTransferred.set(state.getBytesTransferred()));

  task.addOnSuccessListener(taskSnapshot -> semaphore.release(1));

  ControllableSchedulerHelper.getInstance().resume();

  for (int i = 0; i < 3000; i++) {
    Robolectric.flushForegroundThreadScheduler();
    if (semaphore.tryAcquire(2, 1, TimeUnit.MILLISECONDS)) {
      Assert.assertEquals(bytesDownloaded.get(), bytesTransferred.get());
      return;
    }
  }
  fail();
}
 
Example 16
Source File: S2STestService.java    From Openfire with Apache License 2.0 4 votes vote down vote up
/**
 * Run a test against the domain.
 * @return K-V pairs of debug information.
 * @throws Exception On error.
 */
public Map<String, String> run() throws Exception {
    waitUntil = new Semaphore(0);
    Map<String, String> results = new HashMap<>();
    final DomainPair pair = new DomainPair(XMPPServer.getInstance().getServerInfo().getXMPPDomain(), domain);

    // Tear down existing routes.
    final SessionManager sessionManager = SessionManager.getInstance();
    for (final Session incomingServerSession : sessionManager.getIncomingServerSessions( domain ) )
    {
        incomingServerSession.close();
    }

    final Session outgoingServerSession = sessionManager.getOutgoingServerSession( pair );
    if ( outgoingServerSession != null )
    {
        outgoingServerSession.close();
    }

    final IQ pingRequest = new IQ( Type.get );
    pingRequest.setChildElement( "ping", IQPingHandler.NAMESPACE );
    pingRequest.setFrom( pair.getLocal() );
    pingRequest.setTo( domain );

    // Intercept logging.
    final Writer logs = new StringWriter();
    final String appenderName = addAppender( logs );

    // Intercept packets.
    final PacketInterceptor interceptor = new S2SInterceptor( pingRequest );
    InterceptorManager.getInstance().addInterceptor(interceptor);

    // Send ping.
    try
    {
        Log.info( "Sending server to server ping request to " + domain );
        XMPPServer.getInstance().getIQRouter().route( pingRequest );

        // Wait for success or exceed socket timeout.
        waitUntil.tryAcquire( RemoteServerManager.getSocketTimeout(), TimeUnit.MILLISECONDS );

        // Check on the connection status.
        logSessionStatus();

        // Prepare response.
        results.put( "certs", getCertificates() );
        results.put( "stanzas", interceptor.toString() );
        results.put( "logs", logs.toString() );

        return results;
    }
    finally
    {
        // Cleanup
        InterceptorManager.getInstance().removeInterceptor( interceptor );
        removeAppender( appenderName );
    }
}
 
Example 17
Source File: JobLimiterTest.java    From buck with Apache License 2.0 4 votes vote down vote up
@Test
public void testLimitsJobs() throws Exception {
  ListeningExecutorService service =
      MoreExecutors.listeningDecorator(Executors.newFixedThreadPool(10));

  JobLimiter limiter = new JobLimiter(2);

  Semaphore jobStarted = new Semaphore(0);
  Semaphore jobFinished = new Semaphore(0);
  Semaphore jobWaiting = new Semaphore(0);

  AtomicInteger jobsRunning = new AtomicInteger();

  List<ListenableFuture<?>> futures = new ArrayList<>();

  for (int i = 0; i < 10; i++) {
    futures.add(
        limiter.schedule(
            service,
            () ->
                service.submit(
                    () -> {
                      try {
                        assertTrue(jobsRunning.incrementAndGet() <= 2);
                        jobStarted.release();
                        assertTrue(jobWaiting.tryAcquire(2, TimeUnit.SECONDS));
                        jobFinished.release();
                        jobsRunning.decrementAndGet();
                      } catch (InterruptedException e) {
                        throw new RuntimeException();
                      }
                    })));
  }

  // Two jobs should start.
  assertTrue(jobStarted.tryAcquire(50, TimeUnit.MILLISECONDS));
  assertTrue(jobStarted.tryAcquire(50, TimeUnit.MILLISECONDS));

  assertEquals(2, jobsRunning.get());

  for (int i = 0; i < 10; i++) {
    service.submit(() -> {}).get();
  }

  // Third job shouldn't start.
  assertFalse(jobStarted.tryAcquire(50, TimeUnit.MILLISECONDS));

  // Release a waiting job and a new one should start.
  jobWaiting.release();
  assertTrue(jobFinished.tryAcquire(2, TimeUnit.SECONDS));
  assertTrue(jobStarted.tryAcquire(2, TimeUnit.SECONDS));

  // But not a fourth.
  assertFalse(jobStarted.tryAcquire(50, TimeUnit.MILLISECONDS));

  // Let all the jobs but one finish.
  jobWaiting.release(8);
  assertTrue(jobFinished.tryAcquire(8, 2, TimeUnit.SECONDS));

  jobStarted.tryAcquire(7, 2, TimeUnit.SECONDS);
  assertEquals(1, jobsRunning.get());
  // Let the final job finish.
  jobWaiting.release();
  assertTrue(jobFinished.tryAcquire(2, TimeUnit.SECONDS));

  // Ensure all the futures are fulfilled.
  for (ListenableFuture<?> future : futures) {
    future.get(1, TimeUnit.SECONDS);
  }
}
 
Example 18
Source File: TestUtils.java    From FirebaseUI-Android with Apache License 2.0 4 votes vote down vote up
public static ChangeEventListener runAndWaitUntil(
        ObservableSnapshotArray<?> array,
        Runnable task,
        Callable<Boolean> done) throws InterruptedException {

    final Semaphore semaphore = new Semaphore(0);
    ChangeEventListener listener = array.addChangeEventListener(new ChangeEventListener() {
        @Override
        public void onChildChanged(@NonNull ChangeEventType type,
                                   @NonNull DataSnapshot snapshot,
                                   int newIndex,
                                   int oldIndex) {
            semaphore.release();
        }

        @Override
        public void onDataChanged() {
        }

        @Override
        public void onError(@NonNull 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);

    return listener;
}
 
Example 19
Source File: ChromeBrowserSyncAdapter.java    From AndroidChromium with Apache License 2.0 4 votes vote down vote up
@Override
public void onPerformSync(Account account, Bundle extras, String authority,
        ContentProviderClient provider, SyncResult syncResult) {
    if (extras.getBoolean(ContentResolver.SYNC_EXTRAS_INITIALIZE)) {
        Account signedInAccount = ChromeSigninController.get(getContext()).getSignedInUser();
        if (account.equals(signedInAccount)) {
            ContentResolver.setIsSyncable(account, authority, 1);
        } else {
            ContentResolver.setIsSyncable(account, authority, 0);
        }
        return;
    }
    PendingInvalidation invalidation = new PendingInvalidation(extras);

    DelayedInvalidationsController controller = DelayedInvalidationsController.getInstance();
    if (!controller.shouldNotifyInvalidation(extras)) {
        controller.addPendingInvalidation(getContext(), account.name, invalidation);
        return;
    }

    // Browser startup is asynchronous, so we will need to wait for startup to finish.
    Semaphore semaphore = new Semaphore(0);

    // Configure the BrowserParts with all the data it needs.
    BrowserParts parts =
            getBrowserParts(mApplication, account.name, invalidation, syncResult, semaphore);
    startBrowserProcess(parts, syncResult, semaphore);

    try {
        // This code is only synchronously calling a single native method
        // to trigger and asynchronous sync cycle, so 5 minutes is generous.
        if (!semaphore.tryAcquire(5, TimeUnit.MINUTES)) {
            Log.w(TAG, "Sync request timed out!");
            syncResult.stats.numIoExceptions++;
        }
    } catch (InterruptedException e) {
        Log.w(TAG, "Got InterruptedException when trying to request an invalidation.", e);
        // Using numIoExceptions so Android will treat this as a soft error.
        syncResult.stats.numIoExceptions++;
    }
}
 
Example 20
Source File: RemoteMessageRetry.java    From joyqueue with Apache License 2.0 4 votes vote down vote up
@Override
    public List<RetryMessageModel> getRetry(final String topic, final String app, short count, long startIndex) throws
            JoyQueueException {
        checkStarted();

        Semaphore semaphore = this.retrySemaphore;
        if (semaphore.tryAcquire()) {
            try {
                if (topic == null || topic.trim().isEmpty() || app == null || app.trim().isEmpty() || count <= 0) {
                    return new ArrayList<>();
                }

                GetRetry payload = new GetRetry().topic(topic).app(app).count(count).startId(startIndex);
                Command getRetryCommand = new Command(new JoyQueueHeader(Direction.REQUEST, CommandType.GET_RETRY), payload);

                Command ack = sync(getRetryCommand);
                if (ack.getHeader().getStatus() != JoyQueueCode.SUCCESS.getCode()) {
                    throw new JoyQueueException(JoyQueueCode.RETRY_GET, "");
                }


                if (ack != null) {
                    GetRetryAck ackPayload = (GetRetryAck) ack.getPayload();
                    List<RetryMessageModel> messageList = ackPayload.getMessages();
                    if (messageList != null && messageList.size() > 0) {
                        return messageList;
                    }
                }
            } catch (Exception e) {
                logger.error("getRetry exception, topic: {}, app: {}, index: {}, count: {}", topic, app, startIndex, count, e);
//                throw new JoyQueueException(JoyQueueCode.CN_REQUEST_ERROR, e); 远程重试失败,不抛异常,仅记录日志
            } finally {
                if (semaphore != null) {
                    semaphore.release();
                }
            }
        } else {
            if (logger.isDebugEnabled()) {
                logger.debug("tryAcquire failure:" + semaphore.drainPermits());
            }
        }

        return new ArrayList<>();
    }