Package java.util.concurrent.locks

Examples of java.util.concurrent.locks.Condition


            assertEquals("thread not waiting",
                         Thread.State.WAITING, gct.getState());

            // get access to the objects we need
            Lock      lck = mgr.extendedCPBR.poolLock;
            Condition cnd = mgr.extendedCPBR.newestWT.getCondition();

            // Now trigger spurious wakeups. We'll do it several times
            // in a loop, just to be sure the connection manager has a
            // fair chance of misbehaving, and the gct to register it.

            for (int i=0; i<3; i++) {
                if (i > 0)
                    Thread.sleep(333); // don't go too fast

                try {
                    lck.lock();
                    cnd.signalAll(); // this is the spurious wakeup
                } finally {
                    lck.unlock();
                }

                // now give the waiting thread some time to register a wakeup
View Full Code Here


        workqueue = new AutomaticWorkQueueImpl(UNBOUNDED_MAX_QUEUE_SIZE, INITIAL_SIZE,
                                               UNBOUNDED_HIGH_WATER_MARK,
                                               UNBOUNDED_LOW_WATER_MARK,
                                               DEFAULT_DEQUEUE_TIMEOUT);
        final Lock runLock = new ReentrantLock();
        final Condition runCondition = runLock.newCondition();
        long start = System.currentTimeMillis();
        Runnable doNothing = new Runnable() {
            public void run() {
                runLock.lock();
                try {
                    runCondition.signal();
                } finally {
                    runLock.unlock();
                }
            }
        };
       
        workqueue.schedule(doNothing, 5000);
       
        runLock.lock();
        try {
            runCondition.await();
        } finally {
            runLock.unlock();
        }
       
        assertTrue("expected delay",
View Full Code Here

    }
    AtomicBoolean txnFail = new AtomicBoolean(false);
    AtomicInteger callbacksReceived = new AtomicInteger(0);
    AtomicInteger callbacksExpected = new AtomicInteger(0);
    final Lock lock = new ReentrantLock();
    final Condition condition = lock.newCondition();
    if (incrementBuffer != null) {
      incrementBuffer.clear();
    }
    /*
     * Callbacks can be reused per transaction, since they share the same
     * locks and conditions.
     */
    Callback<Object, Object> putSuccessCallback =
            new SuccessCallback<Object, Object>(
            lock, callbacksReceived, condition);
    Callback<Object, Object> putFailureCallback =
            new FailureCallback<Object, Object>(
            lock, callbacksReceived, txnFail, condition);

    Callback<Long, Long> incrementSuccessCallback =
            new SuccessCallback<Long, Long>(
            lock, callbacksReceived, condition);
    Callback<Long, Long> incrementFailureCallback =
            new FailureCallback<Long, Long>(
            lock, callbacksReceived, txnFail, condition);

    Status status = Status.READY;
    Channel channel = getChannel();
    int i = 0;
    try {
      txn = channel.getTransaction();
      txn.begin();
      for (; i < batchSize; i++) {
        Event event = channel.take();
        if (event == null) {
          status = Status.BACKOFF;
          if (i == 0) {
            sinkCounter.incrementBatchEmptyCount();
          } else {
            sinkCounter.incrementBatchUnderflowCount();
          }
          break;
        } else {
          serializer.setEvent(event);
          List<PutRequest> actions = serializer.getActions();
          List<AtomicIncrementRequest> increments = serializer.getIncrements();
          callbacksExpected.addAndGet(actions.size());
          if (!batchIncrements) {
            callbacksExpected.addAndGet(increments.size());
          }

          for (PutRequest action : actions) {
            action.setDurable(enableWal);
            client.put(action).addCallbacks(putSuccessCallback, putFailureCallback);
          }
          for (AtomicIncrementRequest increment : increments) {
            if (batchIncrements) {
              CellIdentifier identifier = new CellIdentifier(increment.key(),
                increment.qualifier());
              AtomicIncrementRequest request
                = incrementBuffer.get(identifier);
              if (request == null) {
                incrementBuffer.put(identifier, increment);
              } else {
                request.setAmount(request.getAmount() + increment.getAmount());
              }
            } else {
              client.atomicIncrement(increment).addCallbacks(
                incrementSuccessCallback, incrementFailureCallback);
            }
          }
        }
      }
      if (batchIncrements) {
        Collection<AtomicIncrementRequest> increments = incrementBuffer.values();
        for (AtomicIncrementRequest increment : increments) {
          client.atomicIncrement(increment).addCallbacks(
            incrementSuccessCallback, incrementFailureCallback);
        }
        callbacksExpected.addAndGet(increments.size());
      }
      client.flush();
    } catch (Throwable e) {
      this.handleTransactionFailure(txn);
      this.checkIfChannelExceptionAndThrow(e);
    }
    if (i == batchSize) {
      sinkCounter.incrementBatchCompleteCount();
    }
    sinkCounter.addToEventDrainAttemptCount(i);

    lock.lock();
    long startTime = System.nanoTime();
    long timeRemaining;
    try {
      while ((callbacksReceived.get() < callbacksExpected.get())
              && !txnFail.get()) {
        timeRemaining = timeout - (System.nanoTime() - startTime);
        timeRemaining = (timeRemaining >= 0) ? timeRemaining : 0;
        try {
          if (!condition.await(timeRemaining, TimeUnit.NANOSECONDS)) {
            txnFail.set(true);
            logger.warn("HBase callbacks timed out. "
                    + "Transaction will be rolled back.");
          }
        } catch (Exception ex) {
View Full Code Here

        workqueue = new AutomaticWorkQueueImpl(UNBOUNDED_MAX_QUEUE_SIZE, INITIAL_SIZE,
                                               UNBOUNDED_HIGH_WATER_MARK,
                                               UNBOUNDED_LOW_WATER_MARK,
                                               DEFAULT_DEQUEUE_TIMEOUT);
        final Lock runLock = new ReentrantLock();
        final Condition runCondition = runLock.newCondition();
        long start = System.currentTimeMillis();
        Runnable doNothing = new Runnable() {
            public void run() {
                runLock.lock();
                try {
                    runCondition.signal();
                } finally {
                    runLock.unlock();
                }
            }
        };
       
        workqueue.schedule(doNothing, 5000);
       
        runLock.lock();
        try {
            runCondition.await();
        } finally {
            runLock.unlock();
        }
       
        assertTrue("expected delay",
View Full Code Here

          }
        }
      });

      Lock startLock = new ReentrantLock();
      Condition startCondition = startLock.newCondition();
      MetaStoreThread.BooleanPointer startedServing = new MetaStoreThread.BooleanPointer();
      startMetaStoreThreads(conf, startLock, startCondition, startedServing);
      startMetaStore(cli.port, ShimLoader.getHadoopThriftAuthBridge(), conf, startLock,
          startCondition, startedServing);
    } catch (Throwable t) {
View Full Code Here

        consumer = clientSession.createConsumer(queue);

        // Ensure we sleep the required amount of time.
        ReentrantLock waitLock = new ReentrantLock();
        Condition wait = waitLock.newCondition();
        final long MILLIS = 1000000L;
        long waitTime = TIME_TO_LIVE * MILLIS;
        while (waitTime > 0)
        {
            try
            {
                waitLock.lock();

                waitTime = wait.awaitNanos(waitTime);
            }
            catch (InterruptedException e)
            {
                //Stop if we are interrupted
                fail(e.getMessage());
View Full Code Here

    }

    public void connect(String host, int port,String virtualHost,String username, String password) throws QpidException
    {

        final Condition negotiationComplete = _lock.newCondition();
        closeOk = _lock.newCondition();
        _lock.lock();

        ClientDelegate connectionDelegate = new ClientDelegate()
        {
            private boolean receivedClose = false;
            public SessionDelegate getSessionDelegate()
            {
                return new ClientSessionDelegate();
            }

            public void exception(Throwable t)
            {
                if (_closedListner != null)
                {
                    _closedListner.onClosed(ErrorCode.CONNECTION_ERROR,ErrorCode.CONNECTION_ERROR.getDesc(),t);
                }
                else
                {
                    throw new RuntimeException("connection closed",t);
                }
            }

            public void closed()
            {
                if (_closedListner != null && !this.receivedClose)
                {
                    _closedListner.onClosed(ErrorCode.CONNECTION_ERROR,ErrorCode.CONNECTION_ERROR.getDesc(),null);
                }
            }

            @Override public void connectionCloseOk(Channel context, ConnectionCloseOk struct)
            {
                _lock.lock();
                try
                {
                    closed = true;
                    this.receivedClose = true;
                    closeOk.signalAll();
                }
                finally
                {
                    _lock.unlock();
                }
            }

            @Override public void connectionClose(Channel context, ConnectionClose connectionClose)
            {
                super.connectionClose(context, connectionClose);
                ErrorCode errorCode = ErrorCode.get(connectionClose.getReplyCode().getValue());
                if (_closedListner == null && errorCode != ErrorCode.NO_ERROR)
                {
                    throw new RuntimeException
                        (new QpidException("Server closed the connection: Reason " +
                                           connectionClose.getReplyText(),
                                           errorCode,
                                           null));
                }
                else
                {
                    _closedListner.onClosed(errorCode, connectionClose.getReplyText(),null);
                }

                this.receivedClose = true;
            }
            @Override public void init(Channel ch, ProtocolHeader hdr)
            {
                // TODO: once the merge is done we'll need to update this code
                // for handling 0.8 protocol version type i.e. major=8 and mino
                if (hdr.getMajor() != 0 || hdr.getMinor() != 10)
                {
                    Client.this.header = hdr;
                    _lock.lock();
                    negotiationComplete.signalAll();
                    _lock.unlock();
                }
            }
        };

        connectionDelegate.setCondition(_lock,negotiationComplete);
        connectionDelegate.setUsername(username);
        connectionDelegate.setPassword(password);
        connectionDelegate.setVirtualHost(virtualHost);

        String transport = System.getProperty("transport","io");
        if (transport.equalsIgnoreCase("nio"))
        {
            _logger.info("using NIO Transport");
            _conn = NioHandler.connect(host, port,connectionDelegate);
        }
        else if (transport.equalsIgnoreCase("io"))
        {
            _logger.info("using Plain IO Transport");
            _conn = IoTransport.connect(host, port,connectionDelegate);
        }
        else
        {
            _logger.info("using MINA Transport");
            _conn = MinaHandler.connect(host, port,connectionDelegate);
           // _conn = NativeHandler.connect(host, port,connectionDelegate);
        }

        // XXX: hardcoded version numbers
        _conn.send(new ProtocolHeader(1, 0, 10));

        try
        {
            negotiationComplete.await(timeout, TimeUnit.MILLISECONDS);
            if (header != null)
            {
                _conn.close();
                throw new ProtocolVersionException(header.getMajor(), header.getMinor());
            }
View Full Code Here

            addToOOCPartition(partition);
          } else {
            existing.addPartition(partition);
          }
        } else {
          Condition newC = wLock.newCondition();
          pending.put(id, newC);
          partitionIds.add(id);
          if (inMemoryPartitions < maxInMemoryPartitions) {
            inMemoryPartitions++;
            states.put(id, State.INACTIVE);
            inactive.put(id, partition);
            notEmpty.signal();
          } else {
            states.put(id, State.OFFLOADING);
            onDisk.put(id, (int) partition.getVertexCount());
            wLock.unlock();
            offloadPartition(partition);
            wLock.lock();
            states.put(id, State.ONDISK);
            newC.signalAll();
          }
        }
        return null;
      } finally {
        wLock.unlock();
View Full Code Here

            }
            oldMemtable.freeze();

            final CommitLogSegment.CommitLogContext ctx = writeCommitLog ? CommitLog.instance().getContext() : null;
            logger_.info(columnFamily_ + " has reached its threshold; switching in a fresh Memtable at " + ctx);
            final Condition condition = submitFlush(oldMemtable);
            memtable_ = new Memtable(this);
            // a second executor that makes sure the onMemtableFlushes get called in the right order,
            // while keeping the wait-for-flush (future.get) out of anything latency-sensitive.
            return commitLogUpdater_.submit(new WrappedRunnable()
            {
                public void runMayThrow() throws InterruptedException, IOException
                {
                    condition.await();
                    if (writeCommitLog)
                    {
                        // if we're not writing to the commit log, we are replaying the log, so marking
                        // the log header with "you can discard anything written before the context" is not valid
                        CommitLog.instance().discardCompletedSegments(table_, columnFamily_, ctx);
View Full Code Here

     * (since, by definition, it started last).
     */
    Condition submitFlush(IFlushable flushable)
    {
        logger_.info("Enqueuing flush of " + flushable);
        final Condition condition = new SimpleCondition();
        flushable.flushAndSignal(condition, flushSorter_, flushWriter_);
        return condition;
    }
View Full Code Here

TOP

Related Classes of java.util.concurrent.locks.Condition

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.