List of usage examples for java.util.concurrent Semaphore Semaphore
public Semaphore(int permits)
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 {//w w w.j a v a 2s . c om 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.recipes.shared.TestSharedCount.java
@Test public void testMultiClients() throws Exception { final int CLIENT_QTY = 5; List<Future<List<Integer>>> futures = Lists.newArrayList(); final List<CuratorFramework> clients = new CopyOnWriteArrayList<CuratorFramework>(); try {/*from ww w . ja v a2s . c o m*/ final CountDownLatch startLatch = new CountDownLatch(CLIENT_QTY); final Semaphore semaphore = new Semaphore(0); ExecutorService service = Executors .newCachedThreadPool(new ThreadFactoryBuilder().setNameFormat("Test-%d").build()); for (int i = 0; i < CLIENT_QTY; ++i) { Future<List<Integer>> future = service.submit(new Callable<List<Integer>>() { @Override public List<Integer> call() throws Exception { final List<Integer> countList = Lists.newArrayList(); CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); clients.add(client); client.start(); SharedCount count = new SharedCount(client, "/count", 10); final CountDownLatch latch = new CountDownLatch(1); count.addListener(new SharedCountListener() { @Override public void countHasChanged(SharedCountReader sharedCount, int newCount) throws Exception { if (newCount < 0) { latch.countDown(); } else { countList.add(newCount); } semaphore.release(); } @Override public void stateChanged(CuratorFramework client, ConnectionState newState) { } }); count.start(); startLatch.countDown(); latch.await(); return countList; } }); futures.add(future); } CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); clients.add(client); client.start(); Assert.assertTrue(startLatch.await(10, TimeUnit.SECONDS)); SharedCount count = new SharedCount(client, "/count", 10); count.start(); List<Integer> countList = Lists.newArrayList(); Random random = new Random(); for (int i = 0; i < 100; ++i) { Thread.sleep(random.nextInt(10)); int next = random.nextInt(100); countList.add(next); count.setCount(next); Assert.assertTrue(semaphore.tryAcquire(CLIENT_QTY, 10, TimeUnit.SECONDS)); } count.setCount(-1); for (Future<List<Integer>> future : futures) { List<Integer> thisCountList = future.get(); Assert.assertEquals(thisCountList, countList); } } finally { for (CuratorFramework client : clients) { IOUtils.closeQuietly(client); } } }
From source file:fr.aliasource.webmail.common.cache.CacheManager.java
public CacheManager(AccountCache cache, IAccount account) { this.logger = LogFactory.getLog(getClass()); this.account = account; this.cache = cache; this.skipCount = 0; this.uidc = new HashMap<IFolder, UIDCache>(); firstIndexingRoundLock = new Semaphore(1); refreshLock = new Semaphore(1); grabFirstLock();// w ww . ja v a2 s .com }
From source file:com.isencia.passerelle.hmi.util.DynamicStepExecutionControlStrategy.java
public DynamicStepExecutionControlStrategy(Director container, String name) throws IllegalActionException, NameDuplicationException { super(container, name); container.setExecutionControlStrategy(this); // this kind of attribute is only for usage inside a IDE or HMI and these will add it everytime it's needed // so we must make sure it's not saved into the model's moml inadvertently... setPersistent(false);/*w w w .j av a 2 s . co m*/ busyActorCount = new Semaphore(0); stepEventCount = new Semaphore(0); }
From source file:oz.hadoop.yarn.api.net.ContainerDelegateImpl.java
/** * //ww w.j ava2 s. co m * @param selectionKey * @param clientServer */ ContainerDelegateImpl(SelectionKey selectionKey, ApplicationContainerServerImpl clientServer) { this.selectionKey = selectionKey; this.clientServer = clientServer; this.executionGovernor = new Semaphore(1); try { this.applicationContainerAddress = (InetSocketAddress) ((SocketChannel) this.selectionKey.channel()) .getLocalAddress(); } catch (Exception e) { throw new IllegalArgumentException("Failed to get Applicatioin Container's address", e); } }
From source file:com.thoughtworks.go.agent.bootstrapper.AgentBootstrapperTest.java
@Test public void shouldNotDieWhenCreationOfLauncherRaisesException() throws InterruptedException { final Semaphore waitForLauncherCreation = new Semaphore(1); waitForLauncherCreation.acquire();/*ww w .j a v a2 s . c om*/ final boolean[] reLaunchWaitIsCalled = new boolean[1]; final AgentBootstrapper bootstrapper = new AgentBootstrapper() { @Override void waitForRelaunchTime() { assertThat(waitTimeBeforeRelaunch, is(0)); reLaunchWaitIsCalled[0] = true; super.waitForRelaunchTime(); } @Override AgentLauncherCreator getLauncherCreator() { return new AgentLauncherCreator() { public AgentLauncher createLauncher() { try { throw new RuntimeException("i bombed"); } finally { if (waitForLauncherCreation.availablePermits() == 0) { waitForLauncherCreation.release(); } } } @Override public void close() { } }; } }; final AgentBootstrapper spyBootstrapper = stubJVMExit(bootstrapper); Thread stopLoopThd = new Thread(new Runnable() { public void run() { try { waitForLauncherCreation.acquire(); } catch (InterruptedException e) { throw new RuntimeException(e); } ReflectionUtil.setField(spyBootstrapper, "loop", false); } }); stopLoopThd.start(); try { spyBootstrapper.go(true, new AgentBootstrapperArgs(new URL("http://" + "ghost-name" + ":" + 3518 + "/go"), null, AgentBootstrapperArgs.SslMode.NONE)); stopLoopThd.join(); } catch (Exception e) { fail("should not have propagated exception thrown while creating launcher"); } assertThat(reLaunchWaitIsCalled[0], is(true)); }
From source file:org.apache.hcatalog.templeton.ExecServiceImpl.java
private ExecServiceImpl() { avail = new Semaphore(appConf.getInt(AppConfig.EXEC_MAX_PROCS_NAME, 16)); }
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 www . j av a2 s .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: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 www . j ava2s.c o m 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.netflix.curator.framework.recipes.leader.TestLeaderSelector.java
@Test public void testAutoRequeue() throws Exception { LeaderSelector selector = null;/*from w w w.j a va2 s. c om*/ 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); } }