Package java.util.concurrent.locks

Examples of java.util.concurrent.locks.Lock


          "Please fix the configuration.");
    }
    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();
    /*
     * 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() + increments.size());

          for (PutRequest action : actions) {
            client.put(action).addCallbacks(putSuccessCallback, putFailureCallback);
          }
          for (AtomicIncrementRequest increment : increments) {
            client.atomicIncrement(increment).addCallbacks(
                    incrementSuccessCallback, incrementFailureCallback);
          }
        }
      }
    } catch (Throwable e) {
      this.handleTransactionFailure(txn);
      this.checkIfChannelExceptionAndThrow(e);
    }
    if (i == batchSize) {
      sinkCounter.incrementBatchCompleteCount();
    }
    sinkCounter.addToEventDrainAttemptCount(i);

    lock.lock();
    try {
      while ((callbacksReceived.get() < callbacksExpected.get())
              && !txnFail.get()) {
        try {
          if(!condition.await(timeout, TimeUnit.MILLISECONDS)){
            txnFail.set(true);
            logger.warn("HBase callbacks timed out. "
                    + "Transaction will be rolled back.");
          }
        } catch (Exception ex) {
          logger.error("Exception while waiting for callbacks from HBase.");
          this.handleTransactionFailure(txn);
          Throwables.propagate(ex);
        }
      }
    } finally {
      lock.unlock();
    }

    /*
     * At this point, either the txn has failed
     * or all callbacks received and txn is successful.
View Full Code Here


                                         SecurityToken token) throws ProtocolException {
        //make sure the request conforms to the OpenSocial visibility rules
        String personId = validateWriteRequest(userId, groupId, appId, token);

        //lock on this user and this application to avoid any potential concurrency issues
        Lock lock = getApplicationDataLock(personId, appId);
        try {
            lock.lock();

            //get the application data for this user and application
            ApplicationData applicationData = applicationDataRepository.getApplicationData(personId, appId);

            //if there is no data, there's nothing to delete, so we're done...
            if (applicationData == null || applicationData.getData() == null) {
                return ImmediateFuture.newInstance(null);
            }

            //remove the fields specified -- empty field set implies remove all, otherwise remove just the fields specified
            Map<String, String> data = applicationData.getData();
            if (fields == null || fields.size() == 0) {
                data.clear();
            } else {
                data.keySet().removeAll(fields);
            }

            //save our changes and return
            applicationDataRepository.save(applicationData);
        } finally {
            lock.unlock();
            lockService.returnLock(lock);
        }
        return ImmediateFuture.newInstance(null);
    }
View Full Code Here

            fields, Map<String, String> values, SecurityToken token) throws ProtocolException {
        //make sure the request conforms to the OpenSocial visibility rules
        String personId = validateWriteRequest(userId, groupId, appId, token);

        //lock on this user and this application to avoid any potential concurrency issues
        Lock lock = getApplicationDataLock(personId, appId);
        try {
            lock.lock();
            //get the application data for this user and application
            ApplicationData applicationData = applicationDataRepository.getApplicationData(personId, appId);

            //if there is no data, create an empty object to store the data in that we'll save when we're done
            if (applicationData == null) {
                applicationData = new ApplicationDataImpl(null, personId, appId, new HashMap<String, String>());
            }

            //if the fields parameter is empty, we can just use the values map directly since this is a full update
            if (fields == null || fields.size() == 0) {
                applicationData.setData(values);
            }
            //if there are keys in the values map that aren't in the fields set, its a bad request
            else if (!fields.containsAll(values.keySet())) {
                throw new ProtocolException(HttpServletResponse.SC_BAD_REQUEST, "Fields parameter must either be empty or contain keys " +
                        "for all name value pairs sent in request.");
            }
            //we have a partial update - we know that the fields set contains keys for all the entries in the values
            //map (due to the check above), so we can just enumerate over it now to finish our work.  So we want to remove
            //any fields found in the fields set that are not found in the values map and update the rest.
            else {
                Map<String, String> data = applicationData.getData();
                for (String field : fields) {
                    //if this field is not in the values map, its a delete
                    if (!values.containsKey(field)) {
                        data.remove(field);
                    } else {
                        //its an update
                        data.put(field, values.get(field));
                    }
                }
            }

            //save our changes and return
            applicationDataRepository.save(applicationData);
        } finally {
            lock.unlock();
            lockService.returnLock(lock);
        }
        return ImmediateFuture.newInstance(null);
    }
View Full Code Here

            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
                Thread.sleep(100);
View Full Code Here

            fail("null condition not detected");
        } catch (IllegalArgumentException iax) {
            // expected
        }

        Lock      lck = new ReentrantLock();
        Condition cnd = lck.newCondition();

        WaitingThread wt = new WaitingThread(cnd, null);
        assertEquals("wrong condition", cnd, wt.getCondition());
        assertNull  ("pool from nowhere", wt.getPool());
        assertNull  ("thread from nowhere", wt.getThread());
View Full Code Here

    }


    public void testAwaitWakeup() throws InterruptedException {

        Lock      lck = new ReentrantLock();
        Condition cnd = lck.newCondition();
        WaitingThread wt = new WaitingThread(cnd, null);

        AwaitThread ath = new AwaitThread(wt, lck, null);
        ath.start();
        Thread.sleep(100); // give extra thread time to block

        assertNull("thread caught exception", ath.getException());
        assertTrue("thread not waiting", ath.isWaiting());
        assertEquals("wrong thread", ath, wt.getThread());

        Thread.sleep(500); // just for fun, let it wait for some time
        // this may fail due to a spurious wakeup
        assertTrue("thread not waiting, spurious wakeup?", ath.isWaiting());

        try {
            lck.lock();
            wt.wakeup();
        } finally {
            lck.unlock();
        }
        ath.join(10000);

        assertFalse("thread still waiting", ath.isWaiting());
        assertNull("thread caught exception", ath.getException());
View Full Code Here

    }


    public void testInterrupt() throws InterruptedException {

        Lock      lck = new ReentrantLock();
        Condition cnd = lck.newCondition();
        WaitingThread wt = new WaitingThread(cnd, null);

        AwaitThread ath = new AwaitThread(wt, lck, null);
        ath.start();
        Thread.sleep(100); // give extra thread time to block
View Full Code Here

    }


    public void testIllegal() throws InterruptedException {

        Lock      lck = new ReentrantLock();
        Condition cnd = lck.newCondition();
        WaitingThread wt = new WaitingThread(cnd, null);

        try {
            lck.lock();
            wt.wakeup();
            fail("missing waiter not detected");
        } catch (IllegalStateException isx) {
            // expected
        } finally {
            lck.unlock();
        }

        AwaitThread ath1 = new AwaitThread(wt, lck, null);
        ath1.start();
        Thread.sleep(100); // give extra thread time to block
View Full Code Here


    @Override
    public void setResources(WebResourceRoot resources) {

        Lock writeLock = resourcesLock.writeLock();
        writeLock.lock();
        WebResourceRoot oldResources = null;
        try {
            if (getState().isAvailable()) {
                throw new IllegalStateException
                    (sm.getString("standardContext.resources.started"));
            }

            oldResources = this.resources;
            if (oldResources == resources)
                return;

            this.resources = resources;
            if (oldResources != null) {
                oldResources.setContext(null);
            }
            if (resources != null) {
                resources.setContext(this);
            }

            support.firePropertyChange("resources", oldResources,
                    resources);
        } finally {
            writeLock.unlock();
        }
    }
View Full Code Here

     */
    public boolean resourcesStop() {

        boolean ok = true;

        Lock writeLock = resourcesLock.writeLock();
        writeLock.lock();
        try {
            if (resources != null) {
                resources.stop();
            }
        } catch (Throwable t) {
            ExceptionUtils.handleThrowable(t);
            log.error(sm.getString("standardContext.resourcesStop"), t);
            ok = false;
        } finally {
            writeLock.unlock();
        }

        return ok;
    }
View Full Code Here

TOP

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

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.