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

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

Introduction

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

Prototype

lock

Source Link

Usage

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

public void close(final String repositoryId) {
    if (!repositoryCache.containsKey(repositoryId)) {
        return;//w w w  . ja  va  2 s. co m
    }

    // lock
    final Lock lock = locksByRepositoryId.get(repositoryId);
    if (lock != null) {
        lock.lock();
    }
    final Repository repository;
    try {

        // remove cached instance
        repository = repositoryCache.remove(repositoryId);

        // remove from state map
        registryState.remove(STATE_REPOSITORY_PREFIX.concat(repositoryId));

        // remove lock
        locksByRepositoryId.remove(repositoryId);
    } finally {
        if (lock != null) {
            lock.unlock();
        }
    }

    // close repository outside lock
    if (null != repository) {
        try {
            repository.close();
        } catch (final Exception e) {
            LOG.error("Error closing repository {}. {}",
                    new Object[] { repositoryId, ExceptionUtils.getRootCauseMessage(e), e });
        }
    }

    // publish new state
    updateRepositoryState();
}

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

/**
 * Returns the repository with the specified id.
 * // w  w  w .j  av  a2  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:jp.aegif.nemaki.cmis.service.impl.VersioningServiceImpl.java

@Override
public void cancelCheckOut(CallContext callContext, String repositoryId, String objectId,
        ExtensionsData extension) {// ww  w  .j  a va  2  s . c  o m

    exceptionService.invalidArgumentRequiredString("objectId", objectId);

    Lock lock = threadLockService.getWriteLock(repositoryId, objectId);

    try {
        lock.lock();
        nemakiCachePool.get(repositoryId).removeCmisCache(objectId);
        // //////////////////
        // General Exception
        // //////////////////
        Document document = contentService.getDocument(repositoryId, objectId);
        exceptionService.objectNotFound(DomainType.OBJECT, document, objectId);
        exceptionService.permissionDenied(callContext, repositoryId, PermissionMapping.CAN_CHECKIN_DOCUMENT,
                document);

        // //////////////////
        // Specific Exception
        // //////////////////
        exceptionService.constraintVersionable(repositoryId, document.getObjectType());

        // //////////////////
        // Body of the method
        // //////////////////
        contentService.cancelCheckOut(callContext, repositoryId, objectId, extension);

        //remove cache

        Document latest = contentService.getDocumentOfLatestVersion(repositoryId,
                document.getVersionSeriesId());
        //Latest document does not exit when pwc is created as the first version
        if (latest != null) {
            Lock latestLock = threadLockService.getWriteLock(repositoryId, latest.getId());
            try {
                latestLock.lock();
                nemakiCachePool.get(repositoryId).removeCmisCache(latest.getId());
            } finally {
                latestLock.unlock();
            }
        }
    } finally {
        lock.unlock();
    }
}

From source file:org.openhab.binding.neeo.internal.handler.NeeoBrainHandler.java

/**
 * Disposes of the bridge by closing/removing the {@link #neeoBrainApi} and canceling/removing any pending
 * {@link #initializeTask()}//from   ww w  . ja va 2  s  . c o  m
 */
@Override
public void dispose() {
    final Lock writerLock = stateLock.writeLock();
    writerLock.lock();
    try {
        final NeeoBrainApi api = neeoBrainApi;
        neeoBrainApi = null;

        NeeoUtil.cancel(initializationTask.getAndSet(null));
        NeeoUtil.cancel(checkStatus.getAndSet(null));

        if (forwardActionServlet != null) {
            forwardActionServlet = null;

            if (api != null) {
                try {
                    api.deregisterForwardActions();
                } catch (IOException e) {
                    logger.debug("IOException occurred deregistering the forward actions: {}", e.getMessage(),
                            e);
                }
            }

            if (servletPath != null) {
                httpService.unregister(servletPath);
                servletPath = null;
            }
        }

        NeeoUtil.close(api);
    } finally {
        writerLock.unlock();
    }
}

From source file:com.mg.framework.service.DatabaseAuditServiceImpl.java

public void auditModify(PostUpdateEvent modifyEvent) {
    if (!isAuditActivated)
        return;/*from   ww  w. j  a  v  a2  s.  co m*/

    try {
        List<Integer> auditedList;
        String[] names;
        Lock lock = entityAuditSetupLock.readLock();
        lock.lock();
        try {
            EntityAuditSetup auditSetup = entityAuditSetup.get(modifyEvent.getPersister().getEntityName());
            if (auditSetup == null || !auditSetup.isAuditModify())
                return;

            auditedList = new ArrayList<Integer>();
            names = modifyEvent.getPersister().getPropertyNames();
            if (!auditSetup.isAuditModifyAllProperties()) {
                for (int i = 0; i < names.length; i++)
                    if (auditSetup.isAuditModifyProperty(names[i]))
                        auditedList.add(i);
            } else {
                for (int i = 0; i < names.length; i++)
                    auditedList.add(i);
            }
        } finally {
            lock.unlock();
        }

        if (auditedList.isEmpty())
            return;

        String[] stateStr = new String[auditedList.size()];
        String[] oldStateStr = new String[auditedList.size()];
        String[] auditedNames = new String[auditedList.size()];

        int j = 0;
        for (int i = 0; i < names.length; i++) {
            if (!auditedList.contains(i))
                continue;

            Type type = modifyEvent.getPersister().getPropertyType(names[i]);
            if (type.isCollectionType())
                continue;

            auditedNames[j] = names[i];
            if (type.isEntityType()) {
                ClassMetadata metadata = modifyEvent.getPersister().getFactory()
                        .getClassMetadata(type.getName());
                stateStr[j] = entityPropertyToString(modifyEvent.getState()[i], metadata);
                oldStateStr[j] = entityPropertyToString(modifyEvent.getOldState()[i], metadata);
            } else {
                stateStr[j] = modifyEvent.getState()[i] == null ? null : modifyEvent.getState()[i].toString();
                oldStateStr[j] = modifyEvent.getOldState()[i] == null ? null
                        : modifyEvent.getOldState()[i].toString();
            }

            j++;
        }

        // ?? ? 
        if (j == 0)
            return;

        //?? ?     ?
        if (names.length > j) {
            auditedNames = (String[]) ArrayUtils.subarray(auditedNames, 0, j);
            stateStr = (String[]) ArrayUtils.subarray(stateStr, 0, j);
            oldStateStr = (String[]) ArrayUtils.subarray(oldStateStr, 0, j);
        }

        sendAuditMessage(new EntityAuditEvent(modifyEvent.getPersister().getEntityName(),
                DatabaseAuditType.MODIFY, modifyEvent.getId().toString(),
                modifyEvent.getPersister().getIdentifierPropertyName(), auditedNames, stateStr, oldStateStr));
    } catch (Exception e) {
        logger.error("audit modify failed", e);
    }
}

From source file:gridool.db.sql.ParallelSQLExecJob.java

private static int invokeCopyIntoTable(@Nonnull final ParallelSQLMapTaskResult result,
        @Nonnull final String outputName, @Nonnull final DBAccessor dba, @Nonnull final LockManager lockMgr,
        @Nonnull final Timings timings) throws GridException {
    final File file = getImportingFile(result, outputName);
    final long filesize = file.length();
    int taskNum = result.getTaskNumber();
    final String tableName = getTaskResultTableName(outputName, taskNum);
    final String sql = constructCopyIntoQuery(file, result, tableName);

    final long mergeTableTime;
    final int affected;
    ReadWriteLock systableLock = lockMgr.obtainLock(DBAccessor.SYS_TABLE_SYMBOL);
    final Lock lock = WORKAROUND_EXLOCK_ON_SYSTBL ? systableLock.writeLock() : systableLock.readLock(); // FIXME REVIEWME why exclusive lock? => sometimes produces wrong result [Trick] read lock for system tables
    final Connection conn = GridDbUtils.getPrimaryDbConnection(dba, true);
    lock.lock();
    final long startMergeTableTime = System.currentTimeMillis();
    try {/* ww w  . jav a2s  .  co m*/
        affected = JDBCUtils.update(conn, sql);
    } catch (SQLException e) {
        LOG.error(e);
        throw new GridException("failed to execute a query: " + sql, e);
    } finally {
        mergeTableTime = System.currentTimeMillis() - startMergeTableTime;
        lock.unlock();

        JDBCUtils.closeQuietly(conn);
        new FileDeletionThread(file, LOG).start();
    }

    int expected = result.getNumRows();
    if (affected != expected) {
        String warnmsg = "COPY INTO TABLE failed [Expected: " + expected + ", Inserted: " + affected + ']';
        LOG.warn(warnmsg);
        throw new GridException(warnmsg);
    }
    synchronized (timings) {
        timings.mergeTableTimes.add(mergeTableTime);
        timings.recievedBytes.add(filesize);
        timings.recievedRecords.add(affected);
    }
    return affected;
}

From source file:jp.aegif.nemaki.cmis.service.impl.VersioningServiceImpl.java

@Override
public ObjectData getObjectOfLatestVersion(CallContext context, String repositoryId, String objectId,
        String versionSeriesId, Boolean major, String filter, Boolean includeAllowableActions,
        IncludeRelationships includeRelationships, String renditionFilter, Boolean includePolicyIds,
        Boolean includeAcl, ExtensionsData extension) {
    // //////////////////
    // General Exception
    // //////////////////
    // Chemistry Atompub calls this method only with objectId
    if (versionSeriesId == null) {
        exceptionService.invalidArgumentRequiredString("objectId", objectId);
        Document d = contentService.getDocument(repositoryId, objectId);
        versionSeriesId = d.getVersionSeriesId();
    }//from   ww  w  .j a  va2 s  .com

    // Default to false
    Boolean _major = (major == null) ? false : major;
    Document document = null;
    if (_major) {
        document = contentService.getDocumentOfLatestMajorVersion(repositoryId, versionSeriesId);
    } else {
        document = contentService.getDocumentOfLatestVersion(repositoryId, versionSeriesId);
    }

    Lock lock = threadLockService.getReadLock(repositoryId, document.getId());

    try {
        lock.lock();

        exceptionService.objectNotFound(DomainType.OBJECT, document, versionSeriesId);
        exceptionService.permissionDenied(context, repositoryId, PermissionMapping.CAN_GET_PROPERTIES_OBJECT,
                document);

        // //////////////////
        // Body of the method
        // //////////////////
        ObjectData objectData = compileService.compileObjectData(context, repositoryId, document, filter,
                includeAllowableActions, includeRelationships, renditionFilter, includeAcl);
        return objectData;

    } finally {
        lock.unlock();
    }
}

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

public void setState(State state) {
    Lock writeLock = lock.writeLock();
    writeLock.lock();
    try {/*from   w ww  . j  av  a2 s .com*/
        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:jp.aegif.nemaki.cmis.service.impl.VersioningServiceImpl.java

@Override
/**/*from   w w w . ja v a2 s.c o  m*/
 * Repository only allow the latest version to be checked out
 */
public void checkOut(CallContext callContext, String repositoryId, Holder<String> objectId,
        ExtensionsData extension, Holder<Boolean> contentCopied) {

    exceptionService.invalidArgumentRequiredHolderString("objectId", objectId);
    String originalId = objectId.getValue();

    Lock lock = threadLockService.getWriteLock(repositoryId, objectId.getValue());

    try {
        lock.lock();
        nemakiCachePool.get(repositoryId).removeCmisCache(originalId);
        // //////////////////
        // General Exception
        // //////////////////
        Document document = contentService.getDocument(repositoryId, objectId.getValue());
        exceptionService.objectNotFound(DomainType.OBJECT, document, objectId.getValue());
        exceptionService.permissionDenied(callContext, repositoryId, PermissionMapping.CAN_CHECKOUT_DOCUMENT,
                document);

        // //////////////////
        // Specific Exception
        // //////////////////
        // CMIS doesn't define the error type when checkOut is performed
        // repeatedly
        exceptionService.constraintAlreadyCheckedOut(repositoryId, document);
        exceptionService.constraintVersionable(repositoryId, document.getObjectType());
        exceptionService.versioning(document);

        // //////////////////
        // Body of the method
        // //////////////////
        Document pwc = contentService.checkOut(callContext, repositoryId, objectId.getValue(), extension);
        objectId.setValue(pwc.getId());
        Holder<Boolean> copied = new Holder<Boolean>(true);
        contentCopied = copied;

    } finally {
        lock.unlock();
    }
}

From source file:jenkins.plugins.git.AbstractGitSCMSource.java

@CheckForNull
@Override//from  ww w .  j a  v a 2s.  c o m
protected SCMRevision retrieve(@NonNull SCMHead head, @NonNull TaskListener listener)
        throws IOException, InterruptedException {
    String cacheEntry = getCacheEntry();
    Lock cacheLock = getCacheLock(cacheEntry);
    cacheLock.lock();
    try {
        File cacheDir = getCacheDir(cacheEntry);
        Git git = Git.with(listener, new EnvVars(EnvVars.masterEnvVars)).in(cacheDir);
        GitClient client = git.getClient();
        client.addDefaultCredentials(getCredentials());
        if (!client.hasGitRepo()) {
            listener.getLogger().println("Creating git repository in " + cacheDir);
            client.init();
        }
        String remoteName = getRemoteName();
        listener.getLogger().println("Setting " + remoteName + " to " + getRemote());
        client.setRemoteUrl(remoteName, getRemote());
        listener.getLogger().println("Fetching " + remoteName + "...");
        List<RefSpec> refSpecs = getRefSpecs();
        client.fetch(remoteName, refSpecs.toArray(new RefSpec[refSpecs.size()]));
        // we don't prune remotes here, as we just want one head's revision
        for (Branch b : client.getRemoteBranches()) {
            String branchName = StringUtils.removeStart(b.getName(), remoteName + "/");
            if (branchName.equals(head.getName())) {
                return new SCMRevisionImpl(head, b.getSHA1String());
            }
        }
        return null;
    } finally {
        cacheLock.unlock();
    }
}