List of usage examples for java.util.concurrent Semaphore tryAcquire
public boolean tryAcquire(long timeout, TimeUnit unit) throws InterruptedException
From source file:org.jbpm.EventCallback.java
public static void waitForEvent(String event, long timeout) { log.debug("waiting for " + event); Semaphore eventSemaphore = getEventSemaphore(event); try {/*from w w w.jav a2s . c om*/ if (eventSemaphore.tryAcquire(timeout, TimeUnit.MILLISECONDS)) { log.debug("received '" + event + "' notification"); } else { log.warn("event '" + event + "' did not occur within " + timeout + " ms"); } } catch (InterruptedException e) { // reassert interruption Thread.currentThread().interrupt(); } }
From source file:org.apache.solr.schema.TestSchemalessBufferedUpdates.java
@Test public void test() throws Exception { DirectUpdateHandler2.commitOnClose = false; final Semaphore logReplay = new Semaphore(0); final Semaphore logReplayFinish = new Semaphore(0); UpdateLog.testing_logReplayHook = () -> { try {/* w w w . j av a 2 s . c o m*/ assertTrue(logReplay.tryAcquire(TIMEOUT, TimeUnit.SECONDS)); } catch (Exception e) { throw new RuntimeException(e); } }; UpdateLog.testing_logReplayFinishHook = logReplayFinish::release; SolrQueryRequest req = req(); UpdateHandler uhandler = req.getCore().getUpdateHandler(); UpdateLog ulog = uhandler.getUpdateLog(); try { assertEquals(UpdateLog.State.ACTIVE, ulog.getState()); // Invalid date will be normalized by ParseDateField URP updateJ(jsonAdd(processAdd(sdoc("id", "1", "f_dt", "2017-01-04"))), params(DISTRIB_UPDATE_PARAM, FROM_LEADER)); assertU(commit()); assertJQ(req("q", "*:*"), "/response/numFound==1"); ulog.bufferUpdates(); assertEquals(UpdateLog.State.BUFFERING, ulog.getState()); // If the ParseDateField URP isn't ahead of the DUP, then the date won't be normalized in the buffered tlog entry, // and the doc won't be indexed on the replaying replica - a warning is logged as follows: // WARN [...] o.a.s.u.UpdateLog REYPLAY_ERR: IOException reading log // org.apache.solr.common.SolrException: Invalid Date String:'2017-01-05' // at org.apache.solr.util.DateMathParser.parseMath(DateMathParser.java:234) // at org.apache.solr.schema.TrieField.createField(TrieField.java:725) [...] updateJ(jsonAdd(processAdd(sdoc("id", "2", "f_dt", "2017-01-05"))), params(DISTRIB_UPDATE_PARAM, FROM_LEADER)); Future<UpdateLog.RecoveryInfo> rinfoFuture = ulog.applyBufferedUpdates(); assertTrue(rinfoFuture != null); assertEquals(UpdateLog.State.APPLYING_BUFFERED, ulog.getState()); logReplay.release(1000); UpdateLog.RecoveryInfo rinfo = rinfoFuture.get(); assertEquals(UpdateLog.State.ACTIVE, ulog.getState()); assertU(commit()); assertJQ(req("q", "*:*"), "/response/numFound==2"); } finally { DirectUpdateHandler2.commitOnClose = true; UpdateLog.testing_logReplayHook = null; UpdateLog.testing_logReplayFinishHook = null; req().close(); } }
From source file:com.aionemu.gameserver.model.TribeRelationCheck.java
void waitAttackResult(Player player) { final Semaphore mainLock = lock; try {/*from www . j ava 2 s . c o m*/ int retries = 60; // Default attack delay is 500 milliseconds while (retries > 0 && !mainLock.tryAcquire(10, TimeUnit.MILLISECONDS)) { retries--; Thread.sleep(10); } } catch (InterruptedException e) { } finally { player.clearAttackedCount(); mainLock.release(); if (!attacked) System.out.println("\tCreature didn't attack " + player.getCommonData().getName()); } }
From source file:fr.xebia.management.statistics.ProfileAspect.java
@Around(value = "execution(* *(..)) && @annotation(profiled)", argNames = "pjp,profiled") public Object profileInvocation(ProceedingJoinPoint pjp, Profiled profiled) throws Throwable { logger.trace("> profileInvocation({},{}", pjp, profiled); MethodSignature jointPointSignature = (MethodSignature) pjp.getStaticPart().getSignature(); // COMPUTE SERVICE STATISTICS NAME Expression nameAsExpression = profiledMethodNameAsExpressionByMethod.get(jointPointSignature.getMethod()); if (nameAsExpression == null) { if (StringUtils.hasLength(profiled.name())) { String nameAsStringExpression = profiled.name(); nameAsExpression = expressionParser.parseExpression(nameAsStringExpression, parserContext); } else {/* w w w . jav a2s . com*/ String fullyQualifiedMethodName = getFullyQualifiedMethodName(// jointPointSignature.getDeclaringTypeName(), // jointPointSignature.getName(), // this.classNameStyle); nameAsExpression = new LiteralExpression(fullyQualifiedMethodName); } } String serviceStatisticsName; if (nameAsExpression instanceof LiteralExpression) { // Optimization : prevent useless objects instantiations serviceStatisticsName = nameAsExpression.getExpressionString(); } else { serviceStatisticsName = nameAsExpression.getValue(new RootObject(pjp), String.class); } // LOOKUP SERVICE STATISTICS ServiceStatistics serviceStatistics = serviceStatisticsByName.get(serviceStatisticsName); if (serviceStatistics == null) { // INSTIANCIATE NEW SERVICE STATISTICS ServiceStatistics newServiceStatistics = new ServiceStatistics(// new ObjectName(this.jmxDomain + ":type=ServiceStatistics,name=" + serviceStatisticsName), // profiled.businessExceptionsTypes(), profiled.communicationExceptionsTypes()); newServiceStatistics.setSlowInvocationThresholdInMillis(profiled.slowInvocationThresholdInMillis()); newServiceStatistics .setVerySlowInvocationThresholdInMillis(profiled.verySlowInvocationThresholdInMillis()); int maxActive; if (StringUtils.hasLength(profiled.maxActiveExpression())) { maxActive = expressionParser.parseExpression(profiled.maxActiveExpression(), parserContext) .getValue(new RootObject(pjp), Integer.class); } else { maxActive = profiled.maxActive(); } newServiceStatistics.setMaxActive(maxActive); newServiceStatistics.setMaxActiveSemaphoreAcquisitionMaxTimeInNanos(TimeUnit.NANOSECONDS .convert(profiled.maxActiveSemaphoreAcquisitionMaxTimeInMillis(), TimeUnit.MILLISECONDS)); ServiceStatistics previousServiceStatistics = serviceStatisticsByName.putIfAbsent(serviceStatisticsName, newServiceStatistics); if (previousServiceStatistics == null) { serviceStatistics = newServiceStatistics; mbeanExporter.registerManagedResource(serviceStatistics); } else { serviceStatistics = previousServiceStatistics; } } // INVOKE AND PROFILE INVOCATION long nanosBefore = System.nanoTime(); Semaphore semaphore = serviceStatistics.getMaxActiveSemaphore(); if (semaphore != null) { boolean acquired = semaphore.tryAcquire( serviceStatistics.getMaxActiveSemaphoreAcquisitionMaxTimeInNanos(), TimeUnit.NANOSECONDS); if (!acquired) { serviceStatistics.incrementServiceUnavailableExceptionCount(); throw new ServiceUnavailableException("Service '" + serviceStatisticsName + "' is unavailable: " + serviceStatistics.getCurrentActive() + " invocations of are currently running"); } } serviceStatistics.incrementCurrentActiveCount(); try { Object returned = pjp.proceed(); return returned; } catch (Throwable t) { serviceStatistics.incrementExceptionCount(t); throw t; } finally { if (semaphore != null) { semaphore.release(); } serviceStatistics.decrementCurrentActiveCount(); long deltaInNanos = System.nanoTime() - nanosBefore; serviceStatistics.incrementInvocationCounterAndTotalDurationWithNanos(deltaInNanos); if (logger.isDebugEnabled()) { logger.debug("< profileInvocation({}): {}ns", serviceStatisticsName, deltaInNanos); } } }
From source file:org.paxle.data.db.impl.CommandDBTest.java
@SuppressWarnings("unchecked") private void storeUnknownLocation() throws InterruptedException { final int MAX = 10; // command-tracker must be called MAX times checking(new Expectations() { {/* w w w. j a va2 s . c o m*/ exactly(MAX).of(cmdTracker).commandCreated(with(equal("org.paxle.data.db.ICommandDB")), with(any(ICommand.class))); } }); // generated test URI LinkedList<URI> knownURIs; LinkedList<URI> testURI = new LinkedList<URI>(); for (int i = 0; i < MAX; i++) { testURI.add(URI.create("http://test.paxle.net/" + i)); } knownURIs = (LinkedList<URI>) testURI.clone(); // store them to DB int knownCount = this.cmdDB.storeUnknownLocations(0, 1, testURI); assertEquals(0, knownCount); // create a dummy data-sink Semaphore s = null; this.cmdDB.setDataSink(new DummyDataSink(s = new Semaphore(-MAX + 1))); // wait for all commands to be enqueued boolean acquired = s.tryAcquire(3, TimeUnit.SECONDS); assertTrue(acquired); // testing if all URI are known to the DB for (URI knownURI : knownURIs) { // command must be marked as crawled boolean known = this.cmdDB.isKnownInDB(knownURI, "CrawledCommand"); assertTrue("Unkown URI: " + knownURI, known); // command must not be enqueued known = this.cmdDB.isKnownInDB(knownURI, "EnqueuedCommand"); assertFalse("Unkown URI: " + knownURI, known); // command must be known to the cache known = this.cmdDB.isKnownInCache(knownURI); assertTrue(known); // command must be known to the bloom filter known = this.cmdDB.isKnownInDoubleURLs(knownURI); assertTrue(known); } }
From source file:org.apache.servicemix.nmr.core.ChannelImpl.java
/** * Synchronously send the exchange/* w w w . ja v a2s . c om*/ * * @param exchange the exchange to send * @param timeout time to wait in milliseconds * @return <code>true</code> if the exchange has been processed succesfully */ public boolean sendSync(Exchange exchange, long timeout) { InternalExchange e = (InternalExchange) exchange; Semaphore lock = e.getRole() == Role.Consumer ? e.getConsumerLock(true) : e.getProviderLock(true); dispatch(e); Thread thread = Thread.currentThread(); String original = thread.getName(); try { if (timeout > 0) { if (!lock.tryAcquire(timeout, TimeUnit.MILLISECONDS)) { throw new TimeoutException(); } } else { thread.setName(original + " (waiting for exchange " + exchange.getId() + ")"); lock.acquire(); } e.setRole(e.getRole() == Role.Consumer ? Role.Provider : Role.Consumer); } catch (InterruptedException ex) { exchange.setError(ex); for (ExchangeListener l : nmr.getListenerRegistry().getListeners(ExchangeListener.class)) { l.exchangeFailed(exchange); } return false; } catch (TimeoutException ex) { exchange.setError(new AbortedException(ex)); for (ExchangeListener l : nmr.getListenerRegistry().getListeners(ExchangeListener.class)) { l.exchangeFailed(exchange); } return false; } finally { thread.setName(original); } return true; }
From source file:com.kurento.kmf.media.HttpGetEndpointAsyncTest.java
@Before public void setup() throws InterruptedException { final Semaphore sem = new Semaphore(0); pipeline.newHttpGetEndpoint().buildAsync(new Continuation<HttpGetEndpoint>() { @Override/*from w ww. j a v a 2 s . com*/ public void onSuccess(HttpGetEndpoint result) { httpEp = result; sem.release(); } @Override public void onError(Throwable cause) { throw new KurentoMediaFrameworkException(cause); } }); Assert.assertTrue(sem.tryAcquire(500, MILLISECONDS)); }
From source file:com.kurento.kmf.media.HttpPostEndpointAsyncTest.java
@Before public void setup() throws InterruptedException { final Semaphore sem = new Semaphore(0); pipeline.newHttpPostEndpoint().buildAsync(new Continuation<HttpPostEndpoint>() { @Override//from ww w . j a v a2s .c o m public void onSuccess(HttpPostEndpoint result) { httpEp = result; sem.release(); } @Override public void onError(Throwable cause) { throw new KurentoMediaFrameworkException(cause); } }); Assert.assertTrue(sem.tryAcquire(500, MILLISECONDS)); }
From source file:org.openhab.io.mqttembeddedbroker.internal.MqttEmbeddedBrokerServiceTest.java
public void waitForConnectionChange(MqttBrokerConnection c, MqttConnectionState expectedState) throws InterruptedException { Semaphore semaphore = new Semaphore(1); semaphore.acquire();// w ww . ja v a 2 s . c om MqttConnectionObserver mqttConnectionObserver = (state, error) -> { if (state == expectedState) { semaphore.release(); } }; c.addConnectionObserver(mqttConnectionObserver); if (c.connectionState() == expectedState) { semaphore.release(); } // Start the connection and wait until timeout or connected callback returns. semaphore.tryAcquire(3000, TimeUnit.MILLISECONDS); c.removeConnectionObserver(mqttConnectionObserver); }