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:jp.aegif.nemaki.cmis.service.impl.VersioningServiceImpl.java

@Override
public void checkIn(CallContext callContext, String repositoryId, Holder<String> objectId, Boolean major,
        Properties properties, ContentStream contentStream, String checkinComment, List<String> policies,
        Acl addAces, Acl removeAces, ExtensionsData extension) {

    exceptionService.invalidArgumentRequiredHolderString("objectId", objectId);

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

    try {//from ww  w.j ava 2s.  c  om
        lock.lock();

        // //////////////////
        // General Exception
        // //////////////////

        Document pwc = contentService.getDocument(repositoryId, objectId.getValue());
        nemakiCachePool.get(repositoryId).removeCmisCache(pwc.getId());

        exceptionService.objectNotFound(DomainType.OBJECT, pwc, objectId.getValue());
        exceptionService.permissionDenied(callContext, repositoryId,
                PermissionMapping.CAN_CANCEL_CHECKOUT_DOCUMENT, pwc);

        // //////////////////
        // Specific Exception
        // //////////////////
        exceptionService.constraintVersionable(repositoryId, pwc.getObjectType());
        // TODO implement
        // exceptionService.streamNotSupported(documentTypeDefinition,
        // contentStream);

        // //////////////////
        // Body of the method
        // //////////////////
        Document checkedIn = contentService.checkIn(callContext, repositoryId, objectId, major, properties,
                contentStream, checkinComment, policies, addAces, removeAces, extension);
        objectId.setValue(checkedIn.getId());

        //refresh latest version
        Document latest = contentService.getDocumentOfLatestVersion(repositoryId, pwc.getVersionSeriesId());
        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.cyberjos.jcconf2014.node.HazelcastHelper.java

/**
 * Sets the given node to be the master node.
 *
 * @param cloudNode the node to become master
 * @return {@code true} if the given node becomes the master node
 *         successfully//from   w ww . ja  v a2s  .c  om
 * @throws NullPointerException if the given node is {@code null}
 */
public synchronized boolean setMaster(final CloudNode cloudNode) {
    Objects.requireNonNull(cloudNode, "The given cloud node must not be null.");

    final Lock lock = Holder.INSTANCE.getInstance().getLock("my-distributed-lock");
    lock.lock();

    try {
        final NodeRecord masterRecord = HazelcastHelper.<NodeRecord>getAtomicReference(MASTER_NODE).get();

        if (masterRecord != null) {
            final long count = Holder.INSTANCE.getInstance().getCluster().getMembers().stream()
                    .filter(member -> StringUtils.equals(masterRecord.getMemberId(), member.getUuid())).count();

            if (count != 0) {
                logger.warn("The master node has already existed: {}", masterRecord);
                return false;
            }

            this.unregisterNode(masterRecord.getNodeName());
        }

        final NodeRecord newMasterRecord = HazelcastHelper.<String, NodeRecord>getMap(ACTIVE_NODES)
                .get(cloudNode.getName());
        HazelcastHelper.getAtomicReference(MASTER_NODE).set(newMasterRecord);
        logger.info("This node has already become the new master node: {}", newMasterRecord);

        if (WORKING_MODE) {
            final Thread thread = new Thread(this.createProducer(cloudNode));
            thread.start();
        }
    } finally {
        lock.unlock();
    }

    return true;
}

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

@Override
public Acl applyAcl(CallContext callContext, String repositoryId, String objectId, Acl acl,
        AclPropagation aclPropagation) {
    exceptionService.invalidArgumentRequired("objectId", objectId);

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

    try {/*w  w w .  java  2s  .  co m*/
        lock.lock();

        // //////////////////
        // General Exception
        // //////////////////

        Content content = contentService.getContent(repositoryId, objectId);
        exceptionService.objectNotFound(DomainType.OBJECT, content, objectId);
        exceptionService.permissionDenied(callContext, repositoryId, PermissionMapping.CAN_APPLY_ACL_OBJECT,
                content);

        // //////////////////
        // Specific Exception
        // //////////////////
        TypeDefinition td = typeManager.getTypeDefinition(repositoryId, content);
        if (!td.isControllableAcl())
            exceptionService.constraint(objectId,
                    "applyAcl cannot be performed on the object whose controllableAcl = false");
        exceptionService.constraintAclPropagationDoesNotMatch(aclPropagation);
        exceptionService.constraintPermissionDefined(repositoryId, acl, objectId);

        // //////////////////
        // Body of the method
        // //////////////////
        //Check ACL inheritance
        boolean inherited = true; //Inheritance defaults to true if nothing input
        List<CmisExtensionElement> exts = acl.getExtensions();
        if (!CollectionUtils.isEmpty(exts)) {
            for (CmisExtensionElement ext : exts) {
                if (ext.getName().equals("inherited")) {
                    inherited = Boolean.valueOf(ext.getValue());
                }
            }
            if (!contentService.getAclInheritedWithDefault(repositoryId, content).equals(inherited))
                content.setAclInherited(inherited);
        }

        jp.aegif.nemaki.model.Acl nemakiAcl = new jp.aegif.nemaki.model.Acl();
        //REPOSITORYDETERMINED or PROPAGATE is considered as PROPAGATE
        boolean objectOnly = (aclPropagation == AclPropagation.OBJECTONLY) ? true : false;
        for (Ace ace : acl.getAces()) {
            if (ace.isDirect()) {
                jp.aegif.nemaki.model.Ace nemakiAce = new jp.aegif.nemaki.model.Ace(ace.getPrincipalId(),
                        ace.getPermissions(), objectOnly);
                nemakiAcl.getLocalAces().add(nemakiAce);
            }
        }

        convertSystemPrinciaplId(repositoryId, nemakiAcl);
        content.setAcl(nemakiAcl);
        contentService.update(repositoryId, content);
        contentService.writeChangeEvent(callContext, repositoryId, content, nemakiAcl, ChangeType.SECURITY);

        nemakiCachePool.get(repositoryId).removeCmisCache(objectId);

        clearCachesRecursively(Executors.newCachedThreadPool(), callContext, repositoryId, content, false);
        writeChangeEventsRecursively(Executors.newCachedThreadPool(), callContext, repositoryId, content,
                false);

        return getAcl(callContext, repositoryId, objectId, false);
    } finally {
        lock.unlock();
    }

}

From source file:org.onosproject.drivers.bmv2.Bmv2FlowRuleProgrammable.java

private Collection<FlowRule> processFlowRules(Collection<FlowRule> rules, Operation operation) {

    if (!init()) {
        return Collections.emptyList();
    }//from   w w w.  j  av a2 s. c o  m

    DeviceId deviceId = handler().data().deviceId();

    Bmv2DeviceAgent deviceAgent;
    try {
        deviceAgent = controller.getAgent(deviceId);
    } catch (Bmv2RuntimeException e) {
        log.error("Failed to get BMv2 device agent: {}", e.explain());
        return Collections.emptyList();
    }

    Bmv2DeviceContext context = contextService.getContext(deviceId);
    if (context == null) {
        log.error("Unable to get device context for {}", deviceId);
        return Collections.emptyList();
    }

    Bmv2FlowRuleTranslator translator = tableEntryService.getFlowRuleTranslator();

    List<FlowRule> processedFlowRules = Lists.newArrayList();

    for (FlowRule rule : rules) {

        Bmv2TableEntry bmv2Entry;

        try {
            bmv2Entry = translator.translate(rule, context);
        } catch (Bmv2FlowRuleTranslatorException e) {
            log.warn("Unable to translate flow rule: {} - {}", e.getMessage(), rule);
            continue; // next rule
        }

        String tableName = bmv2Entry.tableName();
        Bmv2TableEntryReference entryRef = new Bmv2TableEntryReference(deviceId, tableName,
                bmv2Entry.matchKey());

        Lock lock = ENTRY_LOCKS.computeIfAbsent(entryRef, k -> new ReentrantLock());
        lock.lock();
        try {
            // Get from store
            Bmv2FlowRuleWrapper frWrapper = tableEntryService.lookup(entryRef);
            try {
                if (operation == Operation.APPLY) {
                    // Apply entry
                    long entryId;
                    if (frWrapper != null) {
                        // Existing entry.
                        entryId = frWrapper.entryId();
                        // Tentatively delete entry before re-adding.
                        // It might not exist on device due to inconsistencies.
                        silentlyRemove(deviceAgent, entryRef.tableName(), entryId);
                    }
                    // Add entry.
                    entryId = doAddEntry(deviceAgent, bmv2Entry);
                    frWrapper = new Bmv2FlowRuleWrapper(rule, entryId, System.currentTimeMillis());
                } else {
                    // Remove entry
                    if (frWrapper == null) {
                        // Entry not found in map, how come?
                        forceRemove(deviceAgent, entryRef.tableName(), entryRef.matchKey());
                    } else {
                        long entryId = frWrapper.entryId();
                        doRemove(deviceAgent, entryRef.tableName(), entryId, entryRef.matchKey());
                    }
                    frWrapper = null;
                }
                // If here, no exceptions... things went well :)
                processedFlowRules.add(rule);
            } catch (Bmv2RuntimeException e) {
                log.warn("Unable to {} flow rule: {}", operation.name(), e.explain());
            }

            // Update entryRef binding in table entry service.
            if (frWrapper != null) {
                tableEntryService.bind(entryRef, frWrapper);
            } else {
                tableEntryService.unbind(entryRef);
            }
        } finally {
            lock.unlock();
        }
    }

    return processedFlowRules;
}

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

public void execute() {
    Lock readerLock = lock.readLock();
    readerLock.lock();
    try {//  www.j  av a 2 s  . co  m
        boolean execute = false;
        executionCount++;
        if (state == State.SUSPENDED) {
            if (executionCount >= maxSuspendThreshold) {
                execute = true;
            }
        } else if (state == State.BACK_OFF) {
            if (nextSuspendExecutionCount == executionCount) {
                nextSuspendExecutionCount = nextSuspendExecutionCount * backOffFactor;
                execute = true;
            }
        } else if (state == State.SUSPECT || state == State.ACTIVE) {
            execute = true;
        }

        if (!execute) {
            if (log.isDebugEnabled()) {
                log.debug("Skipping the execution because the Registry Fetching is at SUSPENDED state");
            }
            return;
        }

        for (RegistryResourceEntry key : registryResources) {
            if (state == State.ACTIVE) {
                Entry entry = synapseConfiguration.getEntryDefinition(key.getPath());

                if (entry == null) {
                    log.warn("A non remote entry has being specified: " + key.getPath());
                    return;
                }

                if (key.getType().equals(SEQUENCE)) {
                    entry.setMapper(MediatorFactoryFinder.getInstance());
                } else if (key.getType().equals(ENDPOINT)) {
                    entry.setMapper(XMLToEndpointMapper.getInstance());
                }

                fetchEntry(key.getPath());
            }
        }

        lastExecutionTime = System.currentTimeMillis();
    } finally {
        readerLock.unlock();
    }
}

From source file:org.ng200.openolympus.services.TestingService.java

private SolutionJudge compileSolution(final Solution solution, final SolutionJudge judge,
        final Properties properties) throws ExecutionException {
    if (this.dataProvider == null) {
        throw new IllegalStateException("Shared data provider is null!");
    }/*  w  w w.  j  a  v  a2s  .  c o m*/

    final Lock lock = solution.getTask().readLock();
    lock.lock();

    try {
        TestingService.logger.info("Scheduling solution {} for compilation.", solution.getId());

        final JPPFJob job = new JPPFJob();
        job.setDataProvider(this.dataProvider);

        job.setName("Compile solution " + solution.getId());

        job.getSLA().setMaxNodes(1);
        job.getSLA().setPriority((int) (Integer.MAX_VALUE - solution.getId()));
        job.getSLA().setDispatchExpirationSchedule(new JPPFSchedule(20000L));
        job.getSLA().setMaxDispatchExpirations(5);

        TaskContainer taskContainer = taskContainerCache.getTaskContainerForTask(solution.getTask());

        Thread.currentThread().setContextClassLoader(
                new URLClassLoader(taskContainer.getClassLoaderURLs().toArray(new URL[0]),
                        Thread.currentThread().getContextClassLoader()));
        job.add(new JacksonSerializationDelegatingTask<>(new SolutionCompilationTask(judge,
                Lists.from(storageService.getSolutionFile(solution)), properties),
                taskContainer.getClassLoaderURLs()));

        job.setBlocking(false);

        jppfClient.registerClassLoader(taskContainer.getClassLoader(), job.getUuid());
        this.jppfClient.submitJob(job);
        final JsonTaskExecutionResult<SolutionJudge> result = ((JacksonSerializationDelegatingTask<SolutionJudge, SolutionCompilationTask>) job
                .awaitResults().get(0)).getResultOrThrowable();

        if (result.getError() != null) {
            throw result.getError();
        }

        return result.getResult();

    } catch (final Throwable throwable) {
        throw new RuntimeException("Couldn't compile solution: ", throwable);
    } finally {
        lock.unlock();
    }
}

From source file:com.iternox.piggate.samples.PiggateLogin.Activity_Logged.java

public ArrayList<PiggateOffers> getOffers() {
    Lock l = rwLock2.readLock();
    ArrayList<PiggateOffers> result = new ArrayList<PiggateOffers>();
    l.lock();
    try {//  ww  w .j a v a 2  s  .com
        result.addAll(this.internal_offers);
    } catch (Exception ex) {
    } finally {
        l.unlock();
    }
    return result;
}

From source file:com.iternox.piggate.samples.PiggateLogin.Activity_Logged.java

public ArrayList<PiggateBeacon> getPendingBeacons() {
    Lock l = rwLock.readLock();
    ArrayList<PiggateBeacon> result = new ArrayList<PiggateBeacon>();
    l.lock();
    try {// w ww.  j ava2  s . c o m
        result.addAll(this.pending);
        this.pending.clear();
    } catch (Exception ex) {
    } finally {
        l.unlock();
    }
    return result;
}

From source file:net.siegmar.japtproxy.misc.IOHandler.java

/**
 * This method is responsible for fetching remote data (if needed) and
 * sending the data (locally stored, or remotely fetched) to the client.
 *
 * @param requestedData  the requested data
 * @param poolObject     the pool object
 * @param targetResource the remote resource link
 * @param res            the HttpServletResponse object
 * @return true if the file was sent from cache, false otherwise
 * @throws IOException is thrown if a problem occured while sending data
 * @throws net.siegmar.japtproxy.exception.ResourceUnavailableException is thrown if the resource was not found
 *//*from ww w .  j a  v  a  2  s.c om*/
public boolean sendAndSave(final RequestedData requestedData, final PoolObject poolObject,
        final URL targetResource, final HttpServletResponse res)
        throws IOException, ResourceUnavailableException, InitializationException {
    final String lockIdentifier = requestedData.getRequestedResource();
    final ReadWriteLock lock = ResourceLock.obtainLocker(lockIdentifier);
    final Lock readLock = lock.readLock();

    LockStatus lockStatus;

    readLock.lock();
    lockStatus = LockStatus.READ;

    LOG.debug("Obtained readLock for '{}'", lockIdentifier);

    final long poolModification = poolObject.getLastModified();

    FetchedResource fetchedResource = null;
    OutputStream saveOs = null;
    InputStream is = null;

    try {
        if (poolModification != 0) {
            if (!isNewVersionCheckRequired(poolObject, requestedData.getRequestedResource())) {
                LOG.debug("Local object exists and no need to do a version check - sending local object");
                sendLocalFile(poolObject, requestedData.getRequestModifiedSince(), res);
                return true;
            }

            LOG.debug("Local object exists but new version check is required");
        } else {
            LOG.debug("No local object exists - requesting remote host");
        }

        // Get a fetcher (http, ftp) for the current targetResource
        final Fetcher fetcher = fetcherPool.getInstance(targetResource);

        if (fetcher == null) {
            throw new InitializationException("No fetcher found for resource '" + targetResource + "'");
        }

        fetchedResource = fetcher.fetch(targetResource, poolModification, requestedData.getUserAgent());

        final String contentType = fetchedResource.getContentType();
        final long remoteModification = fetchedResource.getLastModified();
        final long contentLength = fetchedResource.getContentLength();

        if (remoteModification != 0 && poolModification > remoteModification) {
            LOG.warn(
                    "Remote object is older than local pool object "
                            + "(Remote timestamp: {} - Local timestamp: {}). "
                            + "Object won't get updated! Check this manually!",
                    Util.getSimpleDateFromTimestamp(remoteModification),
                    Util.getSimpleDateFromTimestamp(poolModification));
        }

        setHeader(res, fetchedResource);

        if (!fetchedResource.isModified()) {
            LOG.debug("Remote resource has no new version - sending local object");
            sendLocalFile(poolObject, requestedData.getRequestModifiedSince(), res);
            return true;
        }

        if (LOG.isDebugEnabled()) {
            if (poolModification != 0) {
                // Pool file exists, but it is out of date
                LOG.debug(
                        "Newer version found (old Last-Modified: {}) - Request '{}', Last-Modified: {}, "
                                + "Content-Type: {}, Content-Length: {}",
                        Util.getSimpleDateFromTimestamp(poolModification), targetResource,
                        Util.getSimpleDateFromTimestamp(remoteModification), contentType, contentLength);
            } else {
                // No pool file exists
                LOG.debug("Request '{}', Last-Modified: {}, Content-Type: {}, Content-Length: {}",
                        targetResource, Util.getSimpleDateFromTimestamp(remoteModification), contentType,
                        contentLength);
            }
        }

        readLock.unlock();
        lock.writeLock().lock();
        lockStatus = LockStatus.WRITE;

        LOG.debug("Obtained writeLock for '{}'", lockIdentifier);

        is = fetchedResource.getInputStream();

        LOG.info("Sending remote object '{}'", poolObject.getName());

        saveOs = new TeeOutputStream(poolObject.getOutputStream(), res.getOutputStream());
        final long bytesCopied = IOUtils.copyLarge(is, saveOs);

        LOG.debug("Data sent to file and client");

        poolObject.setLastModified(remoteModification);

        if (contentLength != -1 && bytesCopied != contentLength) {
            throw new IOException(
                    String.format("Received file has invalid file size - " + "only %d of %d were downloaded",
                            bytesCopied, contentLength));
        }

        poolObject.store();

        return false;
    } catch (final IOException e) {
        // Remove pool file if it was created by this thread
        if (poolModification == 0) {
            poolObject.remove();
        }

        throw e;
    } finally {
        IOUtils.closeQuietly(is);
        IOUtils.closeQuietly(saveOs);

        if (fetchedResource != null) {
            fetchedResource.close();
        }

        if (lockStatus == LockStatus.WRITE) {
            LOG.debug("Released writeLock for '{}'", lockIdentifier);
            lock.writeLock().unlock();
        } else {
            LOG.debug("Released readLock for '{}'", lockIdentifier);
            readLock.unlock();
        }
        ResourceLock.releaseLocker(lockIdentifier);
    }
}

From source file:com.aretha.content.image.AsyncImageLoader.java

/**
 * Cancel a image load request before is was been execute. if you want to
 * cancel it in progress, please see {@link OnImageLoadListener}
 * //  w w w  .ja v  a2 s .co m
 * @param uri
 */
public void cancel(Uri uri) {
    Lock lock = mMainLock.writeLock();
    ImageLoadingTask task = obtainImageLoadingTask(uri, 0, 0, null, false);
    lock.lock();
    mTaskList.remove(task);
    lock.unlock();
}