List of usage examples for java.util.concurrent Semaphore release
public void release()
From source file:com.netflix.curator.framework.recipes.leader.TestLeaderSelector.java
@Test public void testAutoRequeue() throws Exception { LeaderSelector selector = null;/*from w w w .jav a2s . com*/ CuratorFramework client = CuratorFrameworkFactory.builder().connectString(server.getConnectString()) .retryPolicy(new RetryOneTime(1)).sessionTimeoutMs(1000).build(); try { client.start(); final Semaphore semaphore = new Semaphore(0); LeaderSelectorListener listener = new LeaderSelectorListener() { @Override public void takeLeadership(CuratorFramework client) throws Exception { Thread.sleep(10); semaphore.release(); } @Override public void stateChanged(CuratorFramework client, ConnectionState newState) { } }; selector = new LeaderSelector(client, "/leader", listener); selector.autoRequeue(); selector.start(); Assert.assertTrue(semaphore.tryAcquire(2, 10, TimeUnit.SECONDS)); } finally { IOUtils.closeQuietly(selector); IOUtils.closeQuietly(client); } }
From source file:com.netflix.curator.framework.imps.TestFrameworkEdges.java
@Test public void testRetry() throws Exception { final int MAX_RETRIES = 3; final int serverPort = server.getPort(); final CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), 1000, 1000, new RetryOneTime(10)); client.start();/* w w w . j av a2 s. co m*/ try { final AtomicInteger retries = new AtomicInteger(0); final Semaphore semaphore = new Semaphore(0); client.getZookeeperClient().setRetryPolicy(new RetryPolicy() { @Override public boolean allowRetry(int retryCount, long elapsedTimeMs, RetrySleeper sleeper) { semaphore.release(); if (retries.incrementAndGet() == MAX_RETRIES) { try { server = new TestingServer(serverPort); } catch (Exception e) { throw new Error(e); } } return true; } }); server.stop(); // test foreground retry client.checkExists().forPath("/hey"); Assert.assertTrue(semaphore.tryAcquire(MAX_RETRIES, 10, TimeUnit.SECONDS)); semaphore.drainPermits(); retries.set(0); server.stop(); // test background retry client.checkExists().inBackground().forPath("/hey"); Assert.assertTrue(semaphore.tryAcquire(MAX_RETRIES, 10, TimeUnit.SECONDS)); } catch (Throwable e) { Assert.fail("Error", e); } finally { IOUtils.closeQuietly(client); } }
From source file:com.netflix.curator.framework.imps.TestFailedDeleteManager.java
@Test public void testLostSession() throws Exception { Timing timing = new Timing(); CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new ExponentialBackoffRetry(100, 3)); try {//from w ww . j a va 2 s . co m client.start(); client.create().forPath("/test-me"); final CountDownLatch latch = new CountDownLatch(1); final Semaphore semaphore = new Semaphore(0); ConnectionStateListener listener = new ConnectionStateListener() { @Override public void stateChanged(CuratorFramework client, ConnectionState newState) { if ((newState == ConnectionState.LOST) || (newState == ConnectionState.SUSPENDED)) { semaphore.release(); } else if (newState == ConnectionState.RECONNECTED) { latch.countDown(); } } }; client.getConnectionStateListenable().addListener(listener); server.stop(); Assert.assertTrue(timing.acquireSemaphore(semaphore)); try { client.delete().guaranteed().forPath("/test-me"); Assert.fail(); } catch (KeeperException.ConnectionLossException e) { // expected } Assert.assertTrue(timing.acquireSemaphore(semaphore)); timing.sleepABit(); server = new TestingServer(server.getPort(), server.getTempDirectory()); Assert.assertTrue(timing.awaitLatch(latch)); timing.sleepABit(); Assert.assertNull(client.checkExists().forPath("/test-me")); } finally { IOUtils.closeQuietly(client); } }
From source file:com.netflix.curator.framework.imps.TestFailedDeleteManager.java
@Test public void testWithNamespaceAndLostSession() throws Exception { Timing timing = new Timing(); CuratorFramework client = CuratorFrameworkFactory.builder().connectString(server.getConnectString()) .sessionTimeoutMs(timing.session()).connectionTimeoutMs(timing.connection()) .retryPolicy(new ExponentialBackoffRetry(100, 3)).namespace("aisa").build(); try {/*from w w w .j a v a 2s. c o m*/ client.start(); client.create().forPath("/test-me"); final CountDownLatch latch = new CountDownLatch(1); final Semaphore semaphore = new Semaphore(0); ConnectionStateListener listener = new ConnectionStateListener() { @Override public void stateChanged(CuratorFramework client, ConnectionState newState) { if ((newState == ConnectionState.LOST) || (newState == ConnectionState.SUSPENDED)) { semaphore.release(); } else if (newState == ConnectionState.RECONNECTED) { latch.countDown(); } } }; client.getConnectionStateListenable().addListener(listener); server.stop(); Assert.assertTrue(timing.acquireSemaphore(semaphore)); try { client.delete().guaranteed().forPath("/test-me"); Assert.fail(); } catch (KeeperException.ConnectionLossException e) { // expected } Assert.assertTrue(timing.acquireSemaphore(semaphore)); timing.sleepABit(); server = new TestingServer(server.getPort(), server.getTempDirectory()); Assert.assertTrue(timing.awaitLatch(latch)); timing.sleepABit(); Assert.assertNull(client.checkExists().forPath("/test-me")); } finally { IOUtils.closeQuietly(client); } }
From source file:com.netflix.curator.framework.imps.TestFailedDeleteManager.java
@Test public void testWithNamespaceAndLostSessionAlt() throws Exception { Timing timing = new Timing(); CuratorFramework client = CuratorFrameworkFactory.builder().connectString(server.getConnectString()) .sessionTimeoutMs(timing.session()).connectionTimeoutMs(timing.connection()) .retryPolicy(new ExponentialBackoffRetry(100, 3)).build(); try {/*ww w. j a va2 s. c o m*/ client.start(); CuratorFramework namespaceClient = client.usingNamespace("foo"); namespaceClient.create().forPath("/test-me"); final CountDownLatch latch = new CountDownLatch(1); final Semaphore semaphore = new Semaphore(0); ConnectionStateListener listener = new ConnectionStateListener() { @Override public void stateChanged(CuratorFramework client, ConnectionState newState) { if ((newState == ConnectionState.LOST) || (newState == ConnectionState.SUSPENDED)) { semaphore.release(); } else if (newState == ConnectionState.RECONNECTED) { latch.countDown(); } } }; namespaceClient.getConnectionStateListenable().addListener(listener); server.stop(); Assert.assertTrue(timing.acquireSemaphore(semaphore)); try { namespaceClient.delete().guaranteed().forPath("/test-me"); Assert.fail(); } catch (KeeperException.ConnectionLossException e) { // expected } Assert.assertTrue(timing.acquireSemaphore(semaphore)); timing.sleepABit(); server = new TestingServer(server.getPort(), server.getTempDirectory()); Assert.assertTrue(timing.awaitLatch(latch)); timing.sleepABit(); Assert.assertNull(namespaceClient.checkExists().forPath("/test-me")); } finally { IOUtils.closeQuietly(client); } }
From source file:com.parse.ParseOkHttpClientTest.java
private void testParseOkHttpClientExecuteWithInterceptor(boolean isInternalInterceptorTest) throws Exception { // Start mock server server.enqueue(generateServerResponse()); server.start();//from w w w .j a v a2 s . c om ParseHttpClient client = new ParseOkHttpClient(10000, null); // Make ParseHttpRequest ParseHttpRequest parseRequest = generateClientRequest(); final Semaphore done = new Semaphore(0); ParseNetworkInterceptor interceptor = new ParseNetworkInterceptor() { @Override public ParseHttpResponse intercept(Chain chain) throws IOException { done.release(); ParseHttpRequest request = chain.getRequest(); // Verify original request verifyClientRequest(request); // Change request ParseHttpRequest requestAgain = generateInterceptorRequest(); // Proceed ParseHttpResponse parseResponse = chain.proceed(requestAgain); // Verify original response verifyServerResponse(parseResponse); // Change response return generateInterceptorResponse(); } }; // Add interceptor if (isInternalInterceptorTest) { client.addInternalInterceptor(interceptor); } else { client.addExternalInterceptor(interceptor); } // Execute request ParseHttpResponse parseResponse = client.execute(parseRequest); // Make sure interceptor is called assertTrue(done.tryAcquire(5, TimeUnit.SECONDS)); RecordedRequest recordedRequest = server.takeRequest(); // Verify request changed by interceptor verifyInterceptorRequest(recordedRequest); // Verify response changed by interceptor verifyInterceptorResponse(parseResponse); }
From source file:org.chromium.android_webview.test.AwContentsTest.java
private int callDocumentHasImagesSync(final AwContents awContents) throws Throwable, InterruptedException { // Set up a container to hold the result object and a semaphore to // make the test wait for the result. final AtomicInteger val = new AtomicInteger(); final Semaphore s = new Semaphore(0); final Message msg = Message.obtain(new Handler(Looper.getMainLooper()) { @Override//from w ww. j ava2s .c o m public void handleMessage(Message msg) { val.set(msg.arg1); s.release(); } }); runTestOnUiThread(new Runnable() { @Override public void run() { awContents.documentHasImages(msg); } }); assertTrue(s.tryAcquire(WAIT_TIMEOUT_MS, TimeUnit.MILLISECONDS)); int result = val.get(); return result; }
From source file:com.aionemu.gameserver.model.TribeRelationCheck.java
void waitAttackResult(Player player) { final Semaphore mainLock = lock; try {//from w w w .java2 s . c om 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:org.apache.zeppelin.spark.SparkRInterpreter.java
@Override public void open() { // create R script createRScript();//w ww .j a va 2 s.com int backendTimeout = Integer.parseInt(System.getenv().getOrDefault("SPARKR_BACKEND_TIMEOUT", "120")); // Launch a SparkR backend server for the R process to connect to; this will let it see our // Java system properties etc. ZeppelinRBackend sparkRBackend = new ZeppelinRBackend(); Semaphore initialized = new Semaphore(0); Thread sparkRBackendThread = new Thread("SparkR backend") { @Override public void run() { sparkRBackendPort = sparkRBackend.init(); initialized.release(); sparkRBackend.run(); } }; sparkRBackendThread.start(); // Wait for RBackend initialization to finish try { if (initialized.tryAcquire(backendTimeout, TimeUnit.SECONDS)) { // Launch R CommandLine cmd = CommandLine.parse(getProperty("zeppelin.sparkr.r")); cmd.addArgument(scriptPath, false); cmd.addArgument("--no-save", false); // cmd.addArgument(getJavaSparkContext().version(), false); executor = new DefaultExecutor(); outputStream = new ByteArrayOutputStream(); PipedOutputStream ps = new PipedOutputStream(); in = null; try { in = new PipedInputStream(ps); } catch (IOException e1) { throw new InterpreterException(e1); } ins = new BufferedWriter(new OutputStreamWriter(ps)); input = new ByteArrayOutputStream(); PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream, outputStream, in); executor.setStreamHandler(streamHandler); executor.setWatchdog(new ExecuteWatchdog(ExecuteWatchdog.INFINITE_TIMEOUT)); Map env = EnvironmentUtils.getProcEnvironment(); String sparkRInterpreterObjId = sparkRBackend.put(this); String uberdataContextObjId = sparkRBackend.put(getUberdataContext()); env.put("R_PROFILE_USER", scriptPath); env.put("SPARK_HOME", getSparkHome()); env.put("EXISTING_SPARKR_BACKEND_PORT", String.valueOf(sparkRBackendPort)); env.put("SPARKR_INTERPRETER_ID", sparkRInterpreterObjId); env.put("UBERDATA_CONTEXT_ID", uberdataContextObjId); logger.info("executing {} {}", env, cmd.toString()); executor.execute(cmd, env, this); logger.info("executed"); rScriptRunning = true; } else { System.err.println("SparkR backend did not initialize in " + backendTimeout + " seconds"); System.exit(-1); } } catch (InterruptedException e) { new InterpreterException((e)); } catch (IOException e) { new InterpreterException((e)); } }
From source file:org.apache.servicemix.nmr.core.ChannelImpl.java
/** * Deliver an exchange to the endpoint using this channel * * @param exchange the exchange to delivery *//*from w ww . j a va 2 s.c o m*/ public void deliver(final InternalExchange exchange) { if (closed.get()) { throw new ChannelClosedException(); } // Log the exchange if (LOG.isTraceEnabled()) { LOG.trace("Channel " + name + " delivering exchange: " + exchange.display(true)); } else if (LOG.isDebugEnabled()) { LOG.debug("Channel " + name + " delivering exchange: " + exchange.display(false)); } // Handle case where the exchange has been sent synchronously Semaphore lock = exchange.getRole() == Role.Provider ? exchange.getConsumerLock(false) : exchange.getProviderLock(false); if (lock != null) { // Call listeners for (ExchangeListener l : nmr.getListenerRegistry().getListeners(ExchangeListener.class)) { l.exchangeDelivered(exchange); } lock.release(); return; } // Delegate processing to the executor try { this.executor.execute(new ExecutorAwareRunnable() { public void run() { process(exchange); } public boolean shouldRunSynchronously() { return shouldRunSynchronously; } }); } catch (RejectedExecutionException e) { if (closed.get()) { throw new ChannelClosedException(); } else { throw e; } } }