Example usage for java.util.concurrent.locks Lock unlock

List of usage examples for java.util.concurrent.locks Lock unlock

Introduction

In this page you can find the example usage for java.util.concurrent.locks Lock unlock.

Prototype

void unlock();

Source Link

Document

Releases the lock.

Usage

From source file:org.apache.synapse.startup.tasks.RegistryResourceFetcher.java

public void setState(State state) {
    Lock writeLock = lock.writeLock();
    writeLock.lock();/* w  w w . j  av  a 2s .c  om*/
    try {
        if (state == State.ACTIVE) {
            currentFailedCount = 0;
            executionCount = 0;
            nextSuspendExecutionCount = 1;
            lastExecutionTime = 0;
        } else if (state == State.SUSPENDED) {
            currentFailedCount = 0;
            executionCount = 0;
            nextSuspendExecutionCount = 0;
        }
        this.state = state;
    } finally {
        writeLock.unlock();
    }
}

From source file:org.apache.hadoop.hbase.util.ConnectionCache.java

/**
 * Get the cached connection for the current user.
 * If none or timed out, create a new one.
 *//*from   ww w.  j  a v a 2  s. c o  m*/
ConnectionInfo getCurrentConnection() throws IOException {
    String userName = getEffectiveUser();
    ConnectionInfo connInfo = connections.get(userName);
    if (connInfo == null || !connInfo.updateAccessTime()) {
        Lock lock = locker.acquireLock(userName);
        try {
            connInfo = connections.get(userName);
            if (connInfo == null) {
                UserGroupInformation ugi = realUser;
                if (!userName.equals(realUserName)) {
                    ugi = UserGroupInformation.createProxyUser(userName, realUser);
                }
                User user = userProvider.create(ugi);
                Connection conn = ConnectionFactory.createConnection(conf, user);
                connInfo = new ConnectionInfo(conn, userName);
                connections.put(userName, connInfo);
            }
        } finally {
            lock.unlock();
        }
    }
    return connInfo;
}

From source file:com.esofthead.mycollab.module.ecm.esb.impl.SaveContentCommandImpl.java

@Override
public void saveContent(Content content, String createdUser, Integer sAccountId) {
    LOG.debug("Save content {} by {}", BeanUtility.printBeanObj(content), createdUser);
    if (sAccountId == null) {
        return;/*from  www. j av a 2  s  . com*/
    }

    Lock lock = DistributionLockUtil.getLock("ecm-" + sAccountId);
    long totalSize = content.getSize();

    if (StringUtils.isNotBlank(content.getThumbnail())) {
        totalSize += rawContentService.getSize(content.getThumbnail());
    }

    try {
        if (lock.tryLock(1, TimeUnit.HOURS)) {
            DriveInfo driveInfo = driveInfoService.getDriveInfo(sAccountId);
            if (driveInfo.getUsedvolume() == null) {
                driveInfo.setUsedvolume(totalSize);
            } else {
                driveInfo.setUsedvolume(totalSize + driveInfo.getUsedvolume());
            }

            driveInfoService.saveOrUpdateDriveInfo(driveInfo);
        }
    } catch (Exception e) {
        LOG.error("Error while save content " + BeanUtility.printBeanObj(content), e);
    } finally {
        lock.unlock();
    }
}

From source file:com.lonepulse.zombielink.processor.AsyncEndpointTest.java

/**
 * <p>Tests an erroneous asynchronous request where the implementation of the 
 * {@link AsyncHandler#onError(Exception)} callback throws an exception.</p>
 *  /* w w w .  j  a v a  2s .  c  om*/
 * @since 1.3.0
 */
@Test
public final void testAsyncErrorCallbackError() throws InterruptedException {

    String subpath = "/errorcallbackerror", body = "non-JSON-content";

    stubFor(get(urlEqualTo(subpath)).willReturn(aResponse().withStatus(200).withBody(body)));

    final Lock lock = new ReentrantLock();
    final Condition condition = lock.newCondition();

    asyncEndpoint.asyncErrorCallbackError(new AsyncHandler<User>() {

        @Override
        public void onSuccess(HttpResponse httpResponse, User user) {
        }

        @Override
        public void onError(InvocationException error) {

            try {

                throw new IllegalStateException();
            } finally {

                lock.lock();
                condition.signal();
                lock.unlock();
            }
        }
    });

    lock.lock();
    condition.await();
    lock.unlock();

    verify(getRequestedFor(urlEqualTo(subpath)));

    successScenario(); //verify that the asynchronous request executor has survived the exception
}

From source file:com.ery.ertc.estorm.util.ByteBufferArray.java

/**
 * Access(read or write) this buffer array with a position and length as the given array. Here we will only lock one buffer even if it
 * may be need visit several buffers. The consistency is guaranteed by the caller.
 * //  w w  w . j  a  v  a2  s.  c o  m
 * @param start
 *            start offset of this buffer array
 * @param len
 *            The maximum number of bytes to be accessed
 * @param array
 *            The array from/to which bytes are to be read/written
 * @param arrayOffset
 *            The offset within the given array of the first byte to be read or written
 * @param visitor
 *            implement of how to visit the byte buffer
 */
void multiple(long start, int len, byte[] array, int arrayOffset, Visitor visitor) {
    assert len >= 0;
    long end = start + len;
    int startBuffer = (int) (start / bufferSize), startOffset = (int) (start % bufferSize);
    int endBuffer = (int) (end / bufferSize), endOffset = (int) (end % bufferSize);
    assert array.length >= len + arrayOffset;
    assert startBuffer >= 0 && startBuffer < bufferCount;
    assert endBuffer >= 0 && endBuffer < bufferCount || (endBuffer == bufferCount && endOffset == 0);
    if (startBuffer >= locks.length || startBuffer < 0) {
        String msg = "Failed multiple, start=" + start + ",startBuffer=" + startBuffer + ",bufferSize="
                + bufferSize;
        LOG.error(msg);
        throw new RuntimeException(msg);
    }
    int srcIndex = 0, cnt = -1;
    for (int i = startBuffer; i <= endBuffer; ++i) {
        Lock lock = locks[i];
        lock.lock();
        try {
            ByteBuffer bb = buffers[i];
            if (i == startBuffer) {
                cnt = bufferSize - startOffset;
                if (cnt > len)
                    cnt = len;
                bb.limit(startOffset + cnt).position(startOffset);
            } else if (i == endBuffer) {
                cnt = endOffset;
                bb.limit(cnt).position(0);
            } else {
                cnt = bufferSize;
                bb.limit(cnt).position(0);
            }
            visitor.visit(bb, array, srcIndex + arrayOffset, cnt);
            srcIndex += cnt;
        } finally {
            lock.unlock();
        }
    }
    assert srcIndex == len;
}

From source file:com.lonepulse.zombielink.processor.AsyncEndpointTest.java

/**
 * <p>Tests a failed asynchronous request where the implementation of the 
 * {@link AsyncHandler#onFailure(HttpResponse)} callback throws an exception.</p>
 *  //from w  ww  .j av  a  2  s .com
 * @since 1.3.0
 */
@Test
public final void testAsyncFailureCallbackError() throws InterruptedException {

    String subpath = "/failurecallbackerror";

    stubFor(get(urlEqualTo(subpath)).willReturn(aResponse().withStatus(404)));

    final Lock lock = new ReentrantLock();
    final Condition condition = lock.newCondition();

    asyncEndpoint.asyncFailureCallbackError(new AsyncHandler<String>() {

        @Override
        public void onSuccess(HttpResponse httpResponse, String e) {
        }

        @Override
        public void onFailure(HttpResponse httpResponse) {

            try {

                throw new IllegalStateException();
            } finally {

                lock.lock();
                condition.signal();
                lock.unlock();
            }
        }
    });

    lock.lock();
    condition.await();
    lock.unlock();

    verify(getRequestedFor(urlEqualTo(subpath)));

    successScenario(); //verify that the asynchronous request executor has survived the exception
}

From source file:org.eclipse.gyrex.persistence.internal.storage.RepositoryRegistry.java

/**
 * Returns the repository with the specified id.
 * /*from ww w .j  av a 2 s. c o m*/
 * @param repositoryId
 *            the repository id.
 * @return the repository
 * @throws IllegalStateException
 *             if a repository with the specified id is not available
 */
public Repository getRepository(final String repositoryId) throws IllegalStateException {
    if (null == repositoryId) {
        throw new IllegalArgumentException("repository id must not be null");
    }

    if (closed.get()) {
        throw new IllegalStateException("closed");
    }

    // lookup a cached instance
    Repository repository = repositoryCache.get(repositoryId);
    if (null != repository) {
        return repository;
    }

    // get repository definition
    final RepositoryDefinition repositoryDef = getStore().findById(repositoryId);
    if (null == repositoryDef) {
        throw new IllegalStateException(
                MessageFormat.format("The repository with id \"{0}\" could not be found!", repositoryId));
    }

    // create a new instance
    final Lock repositoryCreationLock = getOrCreateRepositoryLock(repositoryId);
    repositoryCreationLock.lock();
    try {
        // make sure the cache is empty
        repository = repositoryCache.get(repositoryId);
        if (null != repository) {
            // use cached repository
            return repository;
        }

        // create the repository
        repository = createRepository(repositoryDef);

        // put the repository instance in the cache
        repositoryCache.put(repositoryId, repository);
    } finally {
        repositoryCreationLock.unlock();
    }

    // register repository in state map
    registryState.put(STATE_REPOSITORY_PREFIX.concat(repositoryId), STATE_ACTIVE);

    // update the repository state (outside lock)
    updateRepositoryState();

    // return the repository
    return repository;
}

From source file:DemandCache.java

/**
 * @see java.util.Map#put(java.lang.Object, java.lang.Object)
 *///  w  w w. j  a  v  a2s.  co m
public V put(K key, V value) {
    Lock lock = theLock.writeLock();
    lock.lock();
    try {
        if (thePurgeTime < System.currentTimeMillis() - 60 * 1000)
            purge();
        CacheValue newValue = new CacheValue();
        newValue.value = value;
        _access(newValue, ACCESS_SET);
        CacheValue oldValue = theCache.put(key, newValue);
        return oldValue == null ? null : oldValue.value;
    } finally {
        lock.unlock();
    }
}

From source file:edu.internet2.middleware.shibboleth.common.attribute.resolver.provider.ShibbolethAttributeResolver.java

/**
 * Resolves the attributes requested in the resolution context or all attributes if no specific attributes were
 * requested. This method does not remove dependency only attributes or attributes that do not contain values.
 * /*from  ww w.j a va 2s  .  c  o  m*/
 * @param resolutionContext current resolution context
 * 
 * @return resolved attributes
 * 
 * @throws AttributeResolutionException thrown if the attributes could not be resolved
 */
protected Map<String, BaseAttribute> resolveAttributes(ShibbolethResolutionContext resolutionContext)
        throws AttributeResolutionException {
    Collection<String> attributeIDs = resolutionContext.getAttributeRequestContext()
            .getRequestedAttributesIds();
    Map<String, BaseAttribute> resolvedAttributes = new HashMap<String, BaseAttribute>();

    // if no attributes requested, then resolve everything
    if (attributeIDs == null || attributeIDs.isEmpty()) {
        log.debug("Specific attributes for principal {} were not requested, resolving all attributes.",
                resolutionContext.getAttributeRequestContext().getPrincipalName());
        attributeIDs = getAttributeDefinitions().keySet();
    }

    Lock readLock = getReadWriteLock().readLock();
    readLock.lock();
    try {
        for (String attributeID : attributeIDs) {
            BaseAttribute resolvedAttribute = resolveAttribute(attributeID, resolutionContext);
            if (resolvedAttribute != null) {
                resolvedAttributes.put(resolvedAttribute.getId(), resolvedAttribute);
            }
        }
    } finally {
        readLock.unlock();
    }

    return resolvedAttributes;
}

From source file:org.geotools.gce.imagemosaic.catalog.GTDataStoreGranuleCatalog.java

@Override
public SimpleFeatureType getType(String typeName) throws IOException {
    final Lock lock = rwLock.readLock();
    try {/*  w  w w . ja  v a  2  s.  c o m*/
        lock.lock();
        checkStore();

        if (this.typeNames.isEmpty() || !this.typeNames.contains(typeName)) {
            return null;
        }
        return tileIndexStore.getSchema(typeName);
    } finally {
        lock.unlock();
    }

}