Package java.util.concurrent

Examples of java.util.concurrent.Semaphore


    ExecutorService es = Executors.newCachedThreadPool();
    DefaultMustacheFactory dmf = new DefaultMustacheFactory();
    dmf.setExecutorService(es);
    final Mustache test = dmf.compile(new StringReader(template), "test");
    final AtomicInteger total = new AtomicInteger();
    final Semaphore semaphore = new Semaphore(100);
    for (int i = 0; i < 100000; i++) {
      semaphore.acquire();
      es.submit(new Runnable() {
        @Override
        public void run() {
          try {
            TestObject testObject = new TestObject(r.nextInt(), r.nextInt(), r.nextInt());
            StringWriter sw = new StringWriter();
            test.execute(sw, testObject).close();
            if (!render(testObject).equals(sw.toString())) {
              total.incrementAndGet();
            }
          } catch (IOException e) {
            // Can't fail
            e.printStackTrace();
            System.exit(1);
          } finally {
            semaphore.release();
          }
        }
      });
    }
    // Wait for them all to complete
    semaphore.acquire(100);
    assertEquals(0, total.intValue());
  }
View Full Code Here


     */
    protected SIPTransaction(SIPTransactionStack newParentStack,
            MessageChannel newEncapsulatedChannel) {

        sipStack = newParentStack;
        this.semaphore = new Semaphore(1,true);
       
        encapsulatedChannel = newEncapsulatedChannel;
        // Record this to check if the address has changed before sending
        // message to avoid possible race condition.
        this.peerPort = newEncapsulatedChannel.getPeerPort();
View Full Code Here

    this.ioSemaphore.release();
  }
  */

  private void leaveIOCriticalSection(String key) {
        Semaphore creationSemaphore = socketCreationMap.get(key);
        if (creationSemaphore != null) {
            creationSemaphore.release();
        }
    }
View Full Code Here

        }
    }

    private void enterIOCriticalSection(String key) throws IOException {
        // http://dmy999.com/article/34/correct-use-of-concurrenthashmap
        Semaphore creationSemaphore = socketCreationMap.get(key);
        if(creationSemaphore == null) {
            Semaphore newCreationSemaphore = new Semaphore(1, true);
            creationSemaphore = socketCreationMap.putIfAbsent(key, newCreationSemaphore);
            if(creationSemaphore == null) {
                creationSemaphore = newCreationSemaphore;      
                if (sipStack.getStackLogger().isLoggingEnabled(StackLogger.TRACE_DEBUG)) {
                    sipStack.getStackLogger().logDebug("new Semaphore added for key " + key);
View Full Code Here

       * @param limit
       */
      GroupBlockingCacheMap(long maxSize, float loadFactor, int limit)
      {
         super(maxSize, loadFactor);
         this.usersLock = new Semaphore(limit);
      }
View Full Code Here

        try
        {
            client = CuratorFrameworkFactory.newClient(cluster.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1));
            client.start();

            final Semaphore             semaphore = new Semaphore(0);
            LeaderSelectorListener      listener = new LeaderSelectorListener()
            {
                @Override
                public void takeLeadership(CuratorFramework client) throws Exception
                {
                    List<String>        names = client.getChildren().forPath("/leader");
                    Assert.assertTrue(names.size() > 0);
                    semaphore.release();
                }

                @Override
                public void stateChanged(CuratorFramework client, ConnectionState newState)
                {
View Full Code Here

            client.start();
            client.sync().forPath("/");

            final AtomicReference<Exception>        error = new AtomicReference<Exception>(null);
            final AtomicReference<String>           lockNode = new AtomicReference<String>(null);
            final Semaphore                         semaphore = new Semaphore(0);
            final CountDownLatch                    lostLatch = new CountDownLatch(1);
            final CountDownLatch                    internalLostLatch = new CountDownLatch(1);
            LeaderSelectorListener                  listener = new LeaderSelectorListener()
            {
                @Override
                public void takeLeadership(CuratorFramework client) throws Exception
                {
                    try
                    {
                        List<String>        names = client.getChildren().forPath("/leader");
                        if ( names.size() != 1 )
                        {
                            semaphore.release();
                            Exception exception = new Exception("Names size isn't 1: " + names.size());
                            error.set(exception);
                            return;
                        }
                        lockNode.set(names.get(0));

                        semaphore.release();
                        if ( !timing.multiple(4).awaitLatch(internalLostLatch) )
                        {
                            error.set(new Exception("internalLostLatch await failed"));
                        }
                    }
                    finally
                    {
                        lostLatch.countDown();
                    }
                }

                @Override
                public void stateChanged(CuratorFramework client, ConnectionState newState)
                {
                    if ( newState == ConnectionState.LOST )
                    {
                        internalLostLatch.countDown();
                    }
                }
            };
            LeaderSelector      selector = new LeaderSelector(client, "/leader", listener);
            selector.start();
            Assert.assertTrue(timing.multiple(4).acquireSemaphore(semaphore));
            if ( error.get() != null )
            {
                throw new AssertionError(error.get());
            }

            Collection<InstanceSpec>    instances = cluster.getInstances();
            cluster.stop();

            Assert.assertTrue(timing.multiple(4).awaitLatch(lostLatch));
            timing.sleepABit();
            Assert.assertFalse(selector.hasLeadership());

            Assert.assertNotNull(lockNode.get());
           
            cluster = new TestingCluster(instances.toArray(new InstanceSpec[instances.size()]));
            cluster.start();

            try
            {
                client.delete().forPath(ZKPaths.makePath("/leader", lockNode.get()));   // simulate the lock deleting due to session expiration
            }
            catch ( Exception ignore )
            {
                // ignore
            }

            Assert.assertTrue(semaphore.availablePermits() == 0);
            Assert.assertFalse(selector.hasLeadership());

            selector.requeue();
            Assert.assertTrue(timing.multiple(4).acquireSemaphore(semaphore));
        }
View Full Code Here

        when(curator.newRetryLoop()).thenReturn(retryLoop);

        final Stat              fakeStat = mock(Stat.class);
        final CountDownLatch    startedLatch = new CountDownLatch(2);
        final CountDownLatch    finishedLatch = new CountDownLatch(2);
        final Semaphore         semaphore = new Semaphore(0);
        when(client.exists(Mockito.<String>any(), anyBoolean())).thenAnswer
        (
            new Answer<Stat>()
            {
                @Override
                public Stat answer(InvocationOnMock invocation) throws Throwable
                {
                    semaphore.acquire();
                    return fakeStat;
                }
            }
        );

        final EnsurePath    ensurePath = new EnsurePath("/one/two/three");
        ExecutorService     service = Executors.newCachedThreadPool();
        for ( int i = 0; i < 2; ++i )
        {
            service.submit
            (
                new Callable<Void>()
                {
                    @Override
                    public Void call() throws Exception
                    {
                        startedLatch.countDown();
                        ensurePath.ensure(curator);
                        finishedLatch.countDown();
                        return null;
                    }
                }
            );
        }

        Assert.assertTrue(startedLatch.await(10, TimeUnit.SECONDS));
        semaphore.release(3);
        Assert.assertTrue(finishedLatch.await(10, TimeUnit.SECONDS));
        verify(client, times(3)).exists(Mockito.<String>any(), anyBoolean());

        ensurePath.ensure(curator);
        verifyNoMoreInteractions(client);
View Full Code Here

        final List<CuratorFramework> clients = new CopyOnWriteArrayList<CuratorFramework>();
        final List<SharedCount> counts = new CopyOnWriteArrayList<SharedCount>();
        try
        {
            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);
                                counts.add(count);

                                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);
            counts.add(count);
            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 )
            {
View Full Code Here

    final AtomicInteger runs = new AtomicInteger(0);
    ExecutorService es = Executors.newCachedThreadPool();
    int range = (int) Math.round(Runtime.getRuntime().availableProcessors() * 1.5 + 1);
    for (int threads = 1; threads < range; threads++) {
      final Semaphore semaphore = new Semaphore(threads);
      {
        long start = System.currentTimeMillis();
        while (true) {
          semaphore.acquire();
          es.submit(new Runnable() {
            @Override
            public void run() {
              parse.execute(new NullWriter(), new Object[] { parent });
              runs.incrementAndGet();
              semaphore.release();
            }
          });
          if (System.currentTimeMillis() - start > TIME * 1000) {
            break;
          }
View Full Code Here

TOP

Related Classes of java.util.concurrent.Semaphore

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.