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:jenkins.plugins.git.AbstractGitSCMSource.java

@CheckForNull
@Override/*from   w w  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();
    }
}

From source file:com.mastfrog.netty.http.client.CookieStore.java

void decorate(HttpRequest req) {
    URL url;// w  w  w.ja  va  2  s  . c o  m
    if (!req.getUri().contains("://")) {
        String host = req.headers().get(Headers.HOST.name());
        url = URL.builder().setPath(req.getUri()).setHost(host).create();
    } else {
        url = URL.parse(req.getUri());
    }
    Lock readLock = lock.readLock();
    readLock.lock();
    try {
        List<Cookie> toSend = new ArrayList<>();
        for (Cookie cookie : cookies) {
            if (checkDomain) {
                if (cookie.getDomain() != null && !cookie.getDomain().equals(url.getHost().toString())) {
                    continue;
                }
            }
            if (checkPath) {
                String pth = cookie.getPath();
                if (pth != null) {
                    String compare = url.getPath().toStringWithLeadingSlash();
                    if (!"/".equals(pth) && !"".equals(pth) && !compare.equals(pth)
                            && !compare.startsWith(pth)) {
                        continue;
                    }
                }
            }
            toSend.add(cookie);
        }
        if (!toSend.isEmpty()) {
            for (Cookie ck : toSend) {
                String headerValue = Headers.COOKIE.toString(new Cookie[] { ck });
                req.headers().add(Headers.COOKIE.name(), headerValue);
            }
        }
    } finally {
        readLock.unlock();
    }
}

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

@Override
/**//from   ww  w. ja  va2 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:net.myrrix.online.ServerRecommender.java

private void removePreference(long userID, long itemID, boolean bulk) {

    // Record datum
    try {//  w w w .  j  a v a  2s.c o m
        generationManager.remove(userID, itemID, bulk);
    } catch (IOException ioe) {
        log.warn("Could not append datum; continuing", ioe);
    }

    Generation generation;
    try {
        generation = getCurrentGeneration();
    } catch (NotReadyException nre) {
        // Corner case -- no model ready so all we can do is record (above). Don't fail the request.
        return;
    }

    ReadWriteLock knownItemLock = generation.getKnownItemLock();

    boolean removeUser = false;
    FastByIDMap<FastIDSet> knownItemIDs = generation.getKnownItemIDs();
    if (knownItemIDs != null) {

        Lock knownItemReadLock = knownItemLock.readLock();
        FastIDSet userKnownItemIDs;
        knownItemReadLock.lock();
        try {
            userKnownItemIDs = knownItemIDs.get(userID);
        } finally {
            knownItemReadLock.unlock();
        }

        if (userKnownItemIDs == null) {
            // Doesn't exist? So ignore this request
            return;
        }

        synchronized (userKnownItemIDs) {
            if (!userKnownItemIDs.remove(itemID)) {
                // Item unknown, so ignore this request
                return;
            }
            removeUser = userKnownItemIDs.isEmpty();
        }
    }

    // We can proceed with the request

    FastByIDMap<float[]> X = generation.getX();

    ReadWriteLock xLock = generation.getXLock();

    if (removeUser) {

        Lock knownItemWriteLock = knownItemLock.writeLock();
        knownItemWriteLock.lock();
        try {
            knownItemIDs.remove(userID);
        } finally {
            knownItemWriteLock.unlock();
        }

        Lock xWriteLock = xLock.writeLock();
        xWriteLock.lock();
        try {
            X.remove(userID);
        } finally {
            xWriteLock.unlock();
        }

    }

}

From source file:net.myrrix.online.ServerRecommender.java

@Override
public List<RecommendedItem> recommendToAnonymous(long[] itemIDs, float[] values, int howMany,
        IDRescorer rescorer) throws NotReadyException, NoSuchItemException {

    Preconditions.checkArgument(howMany > 0, "howMany must be positive");

    float[] anonymousUserFeatures = buildAnonymousUserFeatures(itemIDs, values);

    FastIDSet userKnownItemIDs = new FastIDSet(itemIDs.length);
    for (long itemID : itemIDs) {
        userKnownItemIDs.add(itemID);//from   w ww .jav a 2 s  . c  o m
    }

    float[][] anonymousFeaturesAsArray = { anonymousUserFeatures };

    Generation generation = getCurrentGeneration();
    Lock yLock = generation.getYLock().readLock();
    yLock.lock();
    try {
        return multithreadedTopN(anonymousFeaturesAsArray, userKnownItemIDs, generation.getUserTagIDs(),
                rescorer, howMany, generation.getCandidateFilter());
    } finally {
        yLock.unlock();
    }
}

From source file:org.jivesoftware.openfire.spi.PresenceManagerImpl.java

/**
 * Loads offline presence data for the user into cache.
 *
 * @param username the username./* www.ja  v  a2  s .  c  om*/
 */
private void loadOfflinePresence(String username) {
    Connection con = null;
    PreparedStatement pstmt = null;
    ResultSet rs = null;
    Lock lock = CacheFactory.getLock(username, offlinePresenceCache);
    try {
        lock.lock();
        if (!offlinePresenceCache.containsKey(username) || !lastActivityCache.containsKey(username)) {
            con = DbConnectionManager.getConnection();
            pstmt = con.prepareStatement(LOAD_OFFLINE_PRESENCE);
            pstmt.setString(1, username);
            rs = pstmt.executeQuery();
            if (rs.next()) {
                String offlinePresence = DbConnectionManager.getLargeTextField(rs, 1);
                if (rs.wasNull()) {
                    offlinePresence = NULL_STRING;
                }
                long offlineDate = Long.parseLong(rs.getString(2).trim());
                offlinePresenceCache.put(username, offlinePresence);
                lastActivityCache.put(username, offlineDate);
            } else {
                offlinePresenceCache.put(username, NULL_STRING);
                lastActivityCache.put(username, NULL_LONG);
            }
        }
    } catch (SQLException sqle) {
        Log.error(sqle.getMessage(), sqle);
    } finally {
        DbConnectionManager.closeConnection(rs, pstmt, con);
        lock.unlock();
    }
}

From source file:com.netprogs.minecraft.plugins.social.SocialPerson.java

public <U extends IMessage> void waitOn(WaitState waitState, ICommandType waitCommand, U waitData) {
    Lock lock = rwWaitLock.writeLock();
    lock.lock();/*from  w w  w.j  a  v  a2s .c om*/
    try {
        person.setWaitState(waitState);
        person.setWaitCommand(waitCommand);
        person.setWaitData(waitData);
    } finally {
        lock.unlock();
    }
}

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

@Override
public List<RenditionData> getRenditions(CallContext callContext, String repositoryId, String objectId,
        String renditionFilter, BigInteger maxItems, BigInteger skipCount, ExtensionsData extension) {

    Lock lock = threadLockService.getReadLock(repositoryId, objectId);
    try {// w ww  .j ava2  s  .  c o  m
        lock.lock();

        List<Rendition> renditions = contentService.getRenditions(repositoryId, objectId);

        List<RenditionData> results = new ArrayList<RenditionData>();
        for (Rendition rnd : renditions) {
            RenditionDataImpl data = new RenditionDataImpl(rnd.getId(), rnd.getMimetype(),
                    BigInteger.valueOf(rnd.getLength()), rnd.getKind(), rnd.getTitle(),
                    BigInteger.valueOf(rnd.getWidth()), BigInteger.valueOf(rnd.getHeight()),
                    rnd.getRenditionDocumentId());
            results.add(data);
        }
        return results;
    } finally {
        lock.unlock();
    }
}

From source file:org.jasig.maven.notice.LicenseLookupHelper.java

protected LicenseLookup loadLicenseLookup(Unmarshaller unmarshaller, String licenseLookupFile,
        URL licenseLookupUrl, Lock lock, boolean create) throws MojoFailureException {
    final String licenseLookupKey = licenseLookupUrl.toString();

    lock.lock();/*from w ww  .ja  v  a 2 s.  c o  m*/
    try {
        //Look in the cache to see if the lookup file has already been parsed
        LicenseLookup licenseLookup = LICENSE_LOOKUP_CACHE.get(licenseLookupKey);
        if (licenseLookup != null) {
            logger.info("Loading license lookup mappings from '" + licenseLookupUrl + "' (cached)");
            return licenseLookup;
        }

        //Cache miss, check if we should parse the file, return null if not
        if (!create) {
            return null;
        }

        logger.info("Loading license lookup mappings from '" + licenseLookupUrl + "'");
        InputStream lookupStream = null;
        try {
            lookupStream = licenseLookupUrl.openStream();
            licenseLookup = (LicenseLookup) unmarshaller.unmarshal(lookupStream);
            LICENSE_LOOKUP_CACHE.put(licenseLookupKey, licenseLookup);
            return licenseLookup;
        } catch (IOException e) {
            throw new MojoFailureException(
                    "Failed to read '" + licenseLookupFile + "' from '" + licenseLookupUrl + "'", e);
        } catch (JAXBException e) {
            throw new MojoFailureException(
                    "Failed to parse '" + licenseLookupFile + "' from '" + licenseLookupUrl + "'", e);
        } finally {
            IOUtils.closeQuietly(lookupStream);
        }
    } finally {
        lock.unlock();
    }
}

From source file:org.mule.transport.file.FileMessageReceiver.java

@Override
public void poll() {
    try {//from   w  w  w .  j  av  a 2 s  . co  m
        List<File> files = this.listFiles();
        if (logger.isDebugEnabled()) {
            logger.debug("Files: " + files.toString());
        }
        Comparator<File> comparator = getComparator();
        if (comparator != null) {
            Collections.sort(files, comparator);
        }
        for (File file : files) {
            if (getLifecycleState().isStopping()) {
                break;
            }
            // don't process directories
            if (file.isFile()) {
                Lock fileLock = lockFactory.createLock(file.getName());
                if (fileLock.tryLock()) {
                    try {
                        String fileAbsolutePath = file.getAbsolutePath();
                        try {
                            filesBeingProcessingObjectStore.store(fileAbsolutePath, fileAbsolutePath);
                            if (logger.isDebugEnabled()) {
                                logger.debug(
                                        String.format("Flag for $ stored successfully.", fileAbsolutePath));
                            }
                        } catch (ObjectAlreadyExistsException e) {
                            if (logger.isDebugEnabled()) {
                                logger.debug(String.format("Flag for %s being processed is on. Skipping file.",
                                        fileAbsolutePath));
                            }
                            continue;
                        }
                        if (file.exists()) {
                            processFile(file);
                        }
                    } finally {
                        fileLock.unlock();
                    }
                }
            }
        }
    } catch (Exception e) {
        getConnector().getMuleContext().getExceptionListener().handleException(e);
    }
}