Package java.util.concurrent

Examples of java.util.concurrent.Semaphore


        final CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), 1000, 1000, new RetryOneTime(10));
        client.start();
        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);
        }
View Full Code Here


  @Override
  public void configure(Context context) {
    memoryChannel.configure(context);
    int capacity = context.getInteger(CAPACITY, DEFAULT_CAPACITY);
    if(queueRemaining == null) {
      queueRemaining = new Semaphore(capacity, true);
    } else if(capacity > this.capacity) {
      // capacity increase
      queueRemaining.release(capacity - this.capacity);
    } else if(capacity < this.capacity) {
      queueRemaining.acquireUninterruptibly(this.capacity - capacity);
View Full Code Here

        Thread.currentThread().interrupt();
      }
    } else {
      synchronized(queueLock) {
        queue = new LinkedBlockingDeque<Event>(capacity);
        queueRemaining = new Semaphore(capacity);
        queueStored = new Semaphore(0);
      }
    }

    if (bytesRemaining == null) {
      bytesRemaining = new Semaphore(byteCapacity);
      lastByteCapacity = byteCapacity;
    } else {
      if (byteCapacity > lastByteCapacity) {
        bytesRemaining.release(byteCapacity - lastByteCapacity);
        lastByteCapacity = byteCapacity;
View Full Code Here

      final Checkpoint startScnCp = bstCallback.getCheckpoint();
      Assert.assertNotNull(startScnCp);
      Assert.assertEquals(100L, startScnCp.getBootstrapStartScn().longValue());

      log.info("instrument the client pipeline so that we can intercept and delay the channelClosed message");
      final Semaphore passMessage = new Semaphore(1);
      final CountDownLatch closeSent = new CountDownLatch(1);
      passMessage.acquire();
      conn._channel.getPipeline().addBefore("handler", "closeChannelDelay",
          new SimpleChannelHandler(){
            @Override
            public void channelClosed(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
              closeSent.countDown();
              passMessage.acquire();
              try
              {
                super.channelClosed(ctx, e);
              }
              finally
              {
                passMessage.release();
              }
            }
      });

      final Channel serverChannel = getServerChannelForClientConn(conn);
      Thread asyncChannelClose = new Thread(new Runnable()
      {
        @Override
        public void run()
        {
          log.info("closing server channel");
          serverChannel.close();
          log.info("server channel: closed");
          closeSent.countDown();
        }
      }, "asyncChannelCloseThread");
      asyncChannelClose.setDaemon(true);

      Thread asyncBootstrapReq = new Thread(new Runnable()
      {
        @Override
        public void run()
        {
          conn.requestStream("1", null, 10000, startScnCp, bstCallback);
        }
      }, "asyncBootstrapReqThread");
      asyncBootstrapReq.setDaemon(true);

      log.info("simultaneously closing connection and sending /bootstrap request");
      bstCallback.reset();
      asyncChannelClose.start();
      Assert.assertTrue(closeSent.await(1000, TimeUnit.MILLISECONDS));
      TestUtil.assertWithBackoff(new ConditionCheck()
      {
        @Override
        public boolean check()
        {
          return !conn._channel.isConnected();
        }
      }, "waiting for disconnect on the client side", 1000, log);
      Assert.assertEquals(AbstractNettyHttpConnection.State.CONNECTED, conn.getNetworkState());
      log.info("asynchronously sending /bootstrap");
      asyncBootstrapReq.start();

      log.info("letting channelClose get through");
      TestUtil.assertWithBackoff(new ConditionCheck()
      {
        @Override
        public boolean check()
        {
          return bstCallback.isStreamRequestError();
        }
      }, "wait for streamRequestError callback", 1000, log);
      passMessage.release();
      log.info("finished");
    }
    finally
    {
      conn.close();
View Full Code Here

        JcrResourceBundle resourceBundle = resourceBundleCache.get(key);
        if (resourceBundle != null) {
            log.debug("getResourceBundleInternal({}): got cache hit on first try", key);
        } else {
            if (loadingGuards.get(key) == null) {
                loadingGuards.putIfAbsent(key, new Semaphore(1));
            }
            final Semaphore loadingGuard = loadingGuards.get(key);
            try {
                loadingGuard.acquire();
                resourceBundle = resourceBundleCache.get(key);
                if (resourceBundle != null) {
                    log.debug("getResourceBundleInternal({}): got cache hit on second try", key);
                } else {
                    log.debug("getResourceBundleInternal({}): reading from Repository", key);
                    resourceBundle = createResourceBundle(key.baseName, key.locale);
                    resourceBundleCache.put(key, resourceBundle);
                    registerResourceBundle(key, resourceBundle);
                }
            } catch (InterruptedException e) {
                Thread.interrupted();
            } finally {
                loadingGuard.release();
            }
        }
        log.trace("getResourceBundleInternal({}) ==> {}", key, resourceBundle);
        return resourceBundle;
    }
View Full Code Here

        // The semaphore used to block until all the words have been compared.
        // Use word-2 since we don't process the comparison of the word to
        // itself, and we want one permit to be availabe after the last word is
        // compared.  The negative ensures that the release() must happen before
        // the main thread's acquire() will return.
        final Semaphore comparisons = new Semaphore(0 - (words.size() - 2));

        // loop through all the other words computing their
        // similarity
        int submitted = 0;
        for (String s : words) {

            final String other = s;
           
            // skip if it is ourselves
            if (word.equals(other))
                continue;

             workQueue.offer(new Comparison(
                         comparisons, sspace, vector,
                         other, similarityType, mostSimilar));
        }
       
        try {
            comparisons.acquire();
        } catch (InterruptedException ie) {
            // check whether we were interrupted while still waiting for the
            // comparisons to finish
             if (comparisons.availablePermits() < 1) {
                throw new IllegalStateException(
                    "interrupted while waiting for word comparisons to finish",
                    ie);
             }
        }
View Full Code Here

            new LinkedBlockingQueue<Runnable>();
        for (int i = 0; i < Runtime.getRuntime().availableProcessors(); ++i) {
            Thread t = new WorkerThread(workQueue);
            t.start();
        }
        final Semaphore termsProcessed = new Semaphore(0);
       
        for (int termIndex = 0; termIndex < uniqueTerms; ++termIndex) {
           
            final String term = indexToTerm[termIndex];
            final int i = termIndex;
            workQueue.offer(new Runnable() {
                    public void run() {
                        try {
                        LOGGER.fine(String.format(
                            "processing term %6d/%d: %s", i, uniqueTerms,term));
                        Matrix contexts = getTermContexts(i, termFeatures[i]);
                        senseInduce(term, contexts);
                        } catch (IOException ioe) {
                            ioe.printStackTrace();
                        } finally {
                            termsProcessed.release();
                        }                      
                    }
                });
        }
       
        // Wait until all the documents have been processed
        try {
            termsProcessed.acquire(uniqueTerms);
        } catch (InterruptedException ie) {
            throw new Error("interrupted while waiting for terms to " +
                            "finish reprocessing", ie);
        }       
        LOGGER.info("finished reprocessing all terms");
View Full Code Here

            new LinkedBlockingQueue<Runnable>();
        for (int i = 0; i < numThreads; ++i) {
            Thread t = new WorkerThread(workQueue);
            t.start();
        }
        final Semaphore itemsProcessed = new Semaphore(0);

        // Set up thread safe counters for the final data points we need to
        // report.
        final double testRange = getHighestScore() - getLowestScore();
        final AtomicInteger unanswered = new AtomicInteger();
        final AtomicInteger answered = new AtomicInteger();

        // Set up the data structures for storing the human and computed scores.
        int numQuestions = wordPairToHumanJudgement.size();
        final double[] compScores = new double[numQuestions];
        final double[] humanScores = new double[numQuestions];
       
        // Iterate over each of the questions, offering each one to the work
        // queue so that question evaluations can be done in parrallel.
        int question = 0;
        for (Map.Entry<Pair<String>, Double> e :
                wordPairToHumanJudgement.entrySet()) {

            // Set up final variables for the work queue.
            final Pair<String> p = e.getKey();
            final int index = question;
            final double humanScore = e.getValue();
            question++;

            humanScores[index] = humanScore;

            // Offer a new question to the work queue.
            workQueue.offer(new Runnable() {
                public void run() {
                    Double association = computeAssociation(sspace, p.x, p.y);

                    // Skip questions that cannot be answered with the provided
                    // semantic space.  Store the score for this question as the
                    // minimum double value.
                    if (association == null) {
                        unanswered.incrementAndGet();
                        compScores[index] = Double.MIN_VALUE;
                    } else {
                        answered.incrementAndGet();

                        // Scale the associated result to within the test's
                        // range of values
                        compScores[index] =
                            (association * testRange) + getLowestScore();
                    }
                    itemsProcessed.release();
                }
            });
        }
               
        // Wait
        try {
            itemsProcessed.acquire(numQuestions);
        } catch (InterruptedException ie) {
            throw new Error(ie);
        }

        // Copy over the answered questions to a smaller array so that
View Full Code Here

  private Semaphore        done;
  private List<ByteBuffer> buffers;
  private int              bytes;
 
  public ChannelCallback(){
    this.done    = new Semaphore(1);
    this.buffers = new LinkedList<ByteBuffer>();
    this.bytes   = 0;
   
    this.done.acquireUninterruptibly();
  }
View Full Code Here

            new LinkedBlockingQueue<Runnable>();
        for (int i = 0; i < Runtime.getRuntime().availableProcessors(); ++i) {
            Thread t = new WorkerThread(workQueue);
            t.start();
        }
        final Semaphore documentsRerocessed = new Semaphore(0);        

        for (int d = 0; d < numDocuments; ++d) {
            final int docId = d;

            // This value already has any filtered tokens taken into account,
            // i.e. in only counts those tokens that remain after filtering
            int tokensInDoc = corpusReader.readInt();
            // Read in the document
            final int[] doc = new int[tokensInDoc];
            for (int i = 0; i < tokensInDoc; ++i)
                doc[i] = corpusReader.readInt();

            workQueue.offer(new Runnable() {
                    public void run() {
                        // This method creates the document vector and then adds
                        // that document vector with the reflective semantic
                        // vector for each word occurring in the document
                        LOGGER.fine("reprocessing doc #" + docId);
                        processIntDocument(docToVector.get(docId), doc);
                        documentsRerocessed.release();
                    }
                });
        }
        corpusReader.close();

        // Wait until all the documents have been processed
        try {
            documentsRerocessed.acquire(numDocuments);
        } catch (InterruptedException ie) {
            throw new Error("interrupted while waiting for documents to " +
                            "finish reprocessing", ie);
        }       
        LOGGER.fine("finished reprocessing all documents");
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.